1

我有以下正则表达式

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

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

1 回答 1

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\]. 如果您需要捕获两个$s 和一对\[and之间的文本\],那么您需要像这样的正则表达式:

          <-------------> Match text between \[ and \]
/(\$.*?\$|\\\\\[.*?\\\\\])/
  <----->   Match text between dollars
于 2012-07-08T16:54:43.570 回答