Search code examples
phpregexdelimiterpreg-split

Preg_split captured all result in array


I have a problem with the function preg_split in php

My regexp is

#^(-?[0-9]+)(([+x])(-?[0-9]+))*$#

I want for example transform :

-5+69x45

in an array like this

{
[0] = -5
[1] = +
[2] = 69
[3] = x
[4] = 45
}

My regexp work and math with preg_match

But with preg split I don't have my array

I have a empty array without flag or

{
[0] = -5
[1] = x
[2] = 45
}

With the flag PREG_SPLIT_DELIM_CAPTURE

Where is my error?


Solution

  • I think your misunderstood preg_split.

    The pattern you define is used to split the string, but that means those parts of the string that where matched by your pattern are not included in the resulting array.

    By using the flag PREG_SPLIT_DELIM_CAPTURE content of the capturing groups is added to the resulting array (preg_spit doc).

    #^(-?[0-9]+)(([+x])(-?[0-9]+))*$#
                ^^^^^^^^^^^^^^^^^^
    

    But you have a quantifier here around your two last groups, that means in $2 and $3 is only the last match stored and the first match of this group the "+69" is overwritten, so in your case you get

    $1 = -5
    $2 = x
    $3 = 45