我有以下正则表达式
((\$|(\\\[)).*?(\$|(\\\])))
应该捕获$$
和\[\]
之间的所有内容,然后我在http://gskinner.com/RegExr/上对其进行了测试,并且它正在运行。
PHP变体是(加倍反斜杠)
((\$|(\\\\\[)).*?(\$|(\\\\\])))
我想基于该正则表达式拆分我的文本。我如何判断它只使用第一个(和最大的组)而不是这些小的?
preg_split('/((\$|(\\\\\[)).*?(\$|(\\\\\])))/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
因此对于文本This is my $test$ for something.
我应该得到一个数组
[0] => This is my
[1] => $test$
[2] => for something.
但是我得到了
[0] => This is my
[1] => $test$
[2] => $
[3] =>
[4] => $
[5] => for something.
答案 0 :(得分:2)
你需要这样的东西:
$text = 'This is my $test$ for \[something\] new!';
print_r(preg_split('/(\$.*?\$|\\\\\[.*?\\\\\])/', $text, -1, PREG_SPLIT_DELIM_CAPTURE));
输出:
Array
(
[0] => This is my
[1] => $test$
[2] => for
[3] => \[something\]
[4] => new!
)
Hello $there\]
这样的文本,它会失败。如果您需要在两个$
和一对\[
和\]
之间捕获文本,那么您需要正则表达式:
<-------------> Match text between \[ and \]
/(\$.*?\$|\\\\\[.*?\\\\\])/
<-----> Match text between dollars