LostPhysx
LostPhysx

Reputation: 3641

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?

Upvotes: 2

Views: 150

Answers (2)

Toto
Toto

Reputation: 91385

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
)

Upvotes: 3

Mihai Iorga
Mihai Iorga

Reputation: 39704

Using preg_replace():

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

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

Upvotes: 0

Related Questions