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

时间:2021-04-19 21:39:27

I have some code here:

我这里有一些代码:

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

After execution of these commands i have an array containing:

执行这些命令后,我有一个数组,包含:

{text, hello, stack, overflow, test}

And I want to modify it so i get:

我想修改一下,得到

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

How may I achieve this?

我该如何做到这一点?

2 个解决方案

#1


4  

How about:

如何:

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

output:

输出:

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

#2


0  

Using preg_replace():

使用preg_replace():

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

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

#1


4  

How about:

如何:

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

output:

输出:

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

#2


0  

Using preg_replace():

使用preg_replace():

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

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