我需要一些方法来捕获方括号之间的文本.例如,以下字符串:
[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)
归档时间: |
|
查看次数: |
54241 次 |
最近记录: |