我需要一些方法来捕获方括号外的文本。例如,下面的字符串:
My [ground]name[test]Jhon[random]petor [shorts].
我正在使用下面的preg匹配表达式,但结果不可能是预期的
preg_match_all("/[[^]]*]/", $text, $matches);
它给了我方括号内的结果。
Result :
Array (
[0] => [ground]
[1] => [test]
[2] => [random]
[3] => [shorts]
)
预期输出:
Array (
[0] => [My]
[1] => [name]
[2] => [Jhon]
[3] => [petor]
)
任何帮助都将是伟大的
您可以扩展模式,添加K
以清除到目前为止匹配的内容,然后使用交替来匹配1个或多个单词字符。
[[^][]+]K|w+
查看regex演示
$re = '/[[^][]+]K|w+/';
$str = 'My [ground]name[test]Jhon[random]petor [shorts].';
preg_match_all($re, $str, $matches);
print_r(array_values(array_filter($matches[0])));
输出
Array
(
[0] => My
[1] => name
[2] => Jhon
[3] => petor
)