PHP preg_split有两个分隔符,只捕获一个

时间:2012-08-08 14:58:07

标签: php regex delimiter preg-split

正则表达式真的很差,提前抱歉!

我已尽力解决如何将字符串拆分为具有两个分隔符的数组,并仍然捕获一个并将其包含在最终数组中。 preg_split似乎是理想的,但我的正则表达式让我失望。

例如,如果我有字符串foo = bar AND bar=foo;我想将字符串拆分为空格或=字符但保留=以使数组看起来像:

Array
(
    [0] => foo
    [1] => =
    [2] => bar
    [3] => AND
    [4] => bar
    [5] => =
    [6] => foo
)

不幸的是,我得到了这个:

Array
(
    [0] => foo
    [1] => 
    [2] => =
    [3] => 
    [4] => bar
    [5] => AND
    [6] => bar
    [7] => =
    [8] => foo
)

我已经使用此代码(在PHP中):

<!doctype html>
<?php

$string = 'foo = bar AND bar=foo';

$array = preg_split('/ +|(=)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);

?>
<pre>
<?php

print_r($array);

?>
</pre>

我非常感谢你们给予的任何帮助,谢谢大家!

2 个答案:

答案 0 :(得分:1)

添加PREG_SPLIT_NO_EMPTY标志:

$string = 'foo = bar AND bar=foo';
$array = preg_split('/ +|(=)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

现在,this outputs

Array
(
    [0] => foo
    [1] => =
    [2] => bar
    [3] => AND
    [4] => bar
    [5] => =
    [6] => foo
)

答案 1 :(得分:1)

使用PREG_SPLIT_NO_EMPTY来核对“空”匹配:

$array = preg_split('/ +|(=)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

或者,change the regex使得它不会产生空匹配:

$array = preg_split('/ +|(?<!\G)(=)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);