Reputation: 788
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?
Upvotes: 3
Views: 996
Reputation: 785186
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
)
Upvotes: 1
Reputation: 92986
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
Upvotes: 1