问题
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
回答1:
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.
回答2:
If you only want to split along the decimal, you could also use:
$array = explode('.', $num);
回答3:
You can also use T-Regx tool and you won't have such problems :)
Delimiters are not required
<?php
$num = 99.14;
$pat = "[^a-zA-Z0-9]"; // no delimiters :)
$segments = pattern($pat)->split($num);
print_r($segments);
来源:https://stackoverflow.com/questions/27808966/preg-split-unexpected-behavior