捕获PHP中方括号之间的文本

时间:2022-06-09 02:56:11

I need some way of capturing the text between square brackets. So for example, the following string:

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

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

这是[测试]字符串,[吃]我的[短裤]。

Could be used to create the following array:

可用于创建以下数组:

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

I have the following regex, /\[.*?\]/ but it only captures the first instance, so:

我有以下的regex, /\ *?但它只捕捉到第一个实例,所以:

Array ( [0] => [This] )

How can I get the output I need? Note that the square brackets are NEVER nested, so that's not a concern.

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

1 个解决方案

#1


78  

Matches all strings with brackets:

将所有字符串与括号匹配:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[[^\]]*\]/", $text, $matches);
var_dump($matches[0]);

If You want strings without brackets:

如果你想要没有括号的字符串:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
var_dump($matches[1]);

Alternative, slower version of matching without brackets (using "*" instead of "[^]"):

选择,慢的版本匹配没有括号(用“*”代替“[^]”):

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[(.*?)\]/", $text, $matches);
var_dump($matches[1]);

#1


78  

Matches all strings with brackets:

将所有字符串与括号匹配:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[[^\]]*\]/", $text, $matches);
var_dump($matches[0]);

If You want strings without brackets:

如果你想要没有括号的字符串:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
var_dump($matches[1]);

Alternative, slower version of matching without brackets (using "*" instead of "[^]"):

选择,慢的版本匹配没有括号(用“*”代替“[^]”):

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[(.*?)\]/", $text, $matches);
var_dump($matches[1]);