在PHP中使用方括号之间捕获文本

Chu*_*utt 38 php regex string

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

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

可用于创建以下数组:

Array ( 
     [0] => [This] 
     [1] => [test] 
     [2] => [eat] 
     [3] => [shorts] 
)
Run Code Online (Sandbox Code Playgroud)

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

Array ( [0] => [This] )
Run Code Online (Sandbox Code Playgroud)

如何获得我需要的输出?请注意,方括号永远不会嵌套,所以这不是问题.

Nak*_*aki 97

使用括号匹配所有字符串:

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

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

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

替代,较慢版本的匹配没有括号(使用"*"而不是"[^]"):

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

  • 如果你想要括号之间的字符串:preg_match_all("/\[(.*?)\]/",$ text,$ matches); (9认同)
  • @GertVandeVen:需要反斜杠.preg_match_all("/\\[(.*?)\\]/",$文本,$匹配).可能是网页删除了你的;) (3认同)
  • 如果你的代码是'preg_match_all("/\[([^ \]]*)\] /",$ text,$ matches),那将是最好的. (2认同)