在 PHP 中捕获方括号之间的文本
Posted
技术标签:
【中文标题】在 PHP 中捕获方括号之间的文本【英文标题】:Capturing text between square brackets in PHP 【发布时间】:2012-04-23 16:07:00 【问题描述】:我需要一些方法来捕获方括号之间的文本。例如,下面的字符串:
[This] is a [test] string, [eat] my [shorts].
可用于创建以下数组:
Array (
[0] => [This]
[1] => [test]
[2] => [eat]
[3] => [shorts]
)
我有以下正则表达式 /\[.*?\]/
但它只捕获第一个实例,所以:
Array ( [0] => [This] )
我怎样才能得到我需要的输出?请注意,方括号从不嵌套,所以这不是问题。
【问题讨论】:
【参考方案1】:匹配所有带括号的字符串:
$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[[^\]]*\]/", $text, $matches);
var_dump($matches[0]);
如果你想要不带括号的字符串:
$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
var_dump($matches[1]);
不带括号的另一种较慢的匹配版本(使用“*”而不是“[^]”):
$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[(.*?)\]/", $text, $matches);
var_dump($matches[1]);
【讨论】:
如果你想要括号之间的字符串:preg_match_all("/[(.*?)]/",$text,$matches); @GertVandeVen:需要反斜杠。 preg_match_all("/\[(.*?)\]/",$text,$matches)。可能网络删除了你的 ;) @GertVandeVen 奇怪的是,我现在得到以下信息:Array ( [0] => Array ( [0] => [This] [1] => [test] [2] => [eat] [3] => [shorts] ) [1] => Array ( [0] => This [1] => test [2] => eat [3] => shorts ) )
基本上你现在可以显示:print_r($matches[1]);这只会让你得到括号之间的。
最好是preg_match_all("/\[([^\]]*)\]/", $text, $matches);
以上是关于在 PHP 中捕获方括号之间的文本的主要内容,如果未能解决你的问题,请参考以下文章