简体   繁体   中英

How to Split a string via regular expressions and keep the pattern in output?

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?

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
)

Using preg_replace() :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM