Search code examples
phpregexarraysstringpreg-split

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?


Solution

  • 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
    )