42

我需要一些方法来捕获方括号之间的文本。例如,以下字符串:

[This] is a [test] string, [eat] my [shorts].

可用于创建以下数组:

Array ( 
     [0] => [This] 
     [1] => [test] 
     [2] => [eat] 
     [3] => [shorts] 
)

我有以下正则表达式,/\[.*?\]/但它只捕获第一个实例,所以:

Array ( [0] => [This] )

我怎样才能得到我需要的输出?请注意,方括号从不嵌套,所以这不是问题。

4

1 回答 1

113

匹配所有带括号的字符串:

$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]);
于 2012-04-11T10:53:03.290 回答