Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 439
Jebik Avatar asked Jun 30 '26 09:06

Jebik


2 Answers

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
like image 120
stema Avatar answered Jul 01 '26 23:07

stema


You can use this code:

$str = '-5+69x45';
$arr = 
 preg_split('#([+x]|-?\d+)#', $str, 0, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY );
print_r($arr);

OUTPUT:

Array
(
    [0] => -5
    [1] => +
    [2] => 69
    [3] => x
    [4] => 45
)
like image 37
anubhava Avatar answered Jul 01 '26 21:07

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!