如何通过正则表达式拆分字符串并将模式保留在输出中?

时间:2012-10-08 10:13:26

标签: php regex arrays string preg-split

我在这里有一些代码:

$testString = "text23hello54stack90overflow34test";
$testArray = preg_split("/[0-9]{2}/Uim", $testString);
echo "<pre>".print_r($testArray)."</pre>";

执行这些命令后,我有一个包含以下内容的数组:

{text, hello, stack, overflow, test}

我想修改它,所以我得到:

{text, 23hello, 54stack, 90overflow, 34test}

我怎么能实现这个目标?

2 个答案:

答案 0 :(得分:4)

怎么样:

$testString = "text23hello54stack90overflow34test";
$testArray = preg_split("/(?=[0-9]{2})/Uim", $testString);
echo print_r($testArray);

<强>输出:

Array
(
    [0] => text
    [1] => 23hello
    [2] => 54stack
    [3] => 90overflow
    [4] => 34test
)

答案 1 :(得分:0)

使用preg_replace()

$testString = "text23hello54stack90overflow34test";
$testArray = preg_replace("/([0-9]{2})/Uim", ', $1', $testString);

echo $testArray;
// text, 23hello, 54stack, 90overflow, 34test