PHP regex preg_split - 仅按最大组拆分

时间:2012-07-08 16:40:35

标签: php regex preg-split

我有以下正则表达式

((\$|(\\\[)).*?(\$|(\\\])))

应该捕获$$\[\]之间的所有内容,然后我在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.

1 个答案:

答案 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