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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10104473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:23:26  来源:igfitidea点击:

Capturing text between square brackets in PHP

phpregexstring

提问by Chuck Le Butt

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].

[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:

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

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.

我怎样才能得到我需要的输出?请注意,方括号从不嵌套,因此不必担心。

回答by Naki

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]);