Reputation: 13534
I use preg_split as the following:
<?php
$num = 99.14;
$pat = "[^a-zA-Z0-9]";
$segments = preg_split($pat, $num);
print_r($segments);
I expected that $segments will be an array like array(99,14)
However, it returns array(99.14)
I don't know why preg_split do that while the pattern by which it should split the string is any special character i.e non alphanumeric.
Check this demo: http://codepad.org/MUusnwis
Upvotes: 0
Views: 115
Reputation: 2973
You can also use T-Regx tool and you won't have such problems :)
Delimiters are not required
<?php
$num = 99.14;
$segments = pattern("[^a-zA-Z0-9]")->split($num);
print_r($segments);
Upvotes: 0
Reputation: 59681
You have to add delimiters to your regex like this:
<?php
$num = 99.14;
$pat = "/[^a-zA-Z0-9]/";
//^------------^Delmimiter here
$segments = preg_split($pat, $num);
print_r($segments);
?>
Output:
Array ( [0] => 99 [1] => 14 )
EDIT:
The question why OP got the entire string back in the array is simple! If you read the manual here: http://php.net/manual/en/function.preg-split.php
And take a quick quote from there under notes:
Tip If matching fails, an array with a single element containing the input string will be returned.
Upvotes: 4
Reputation: 346
If you only want to split along the decimal, you could also use:
$array = explode('.', $num);
Upvotes: 0