在 PHP 中捕获方括号之间的文本
问题描述:
我需要某种方法来捕获方括号之间的文本.例如,以下字符串:
I need some way of capturing the text between square brackets. So for example, the following string:
【这个】是一个【测试】字符串,【吃】我的【短裤】.
可用于创建以下数组:
Array (
[0] => [This]
[1] => [test]
[2] => [eat]
[3] => [shorts]
)
我有以下正则表达式,/[.*?]/
但它只捕获第一个实例,所以:
I have the following regex, /[.*?]/
but it only captures the first instance, so:
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.
答
匹配所有带括号的字符串:
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]);