regex - How to split negative and positive values in string using php? -
regex - How to split negative and positive values in string using php? -
i have string variable in php, "0+1.65+0.002-23.9
", , want split in individual values.
ex:
0 1.65 0.002 -23.9
i seek with:
$keys = preg_split("/^[+-]?\\d+(\\.\\d+)?$/", $data);
but not work expected.
can help me out? lot in advance.
like this:
$yourstring = "0+1.65+0.002-23.9"; $regex = '~\+|(?=-)~'; $splits = preg_split($regex, $yourstring); print_r($splits);
output (see live php demo):
[0] => 0 [1] => 1.65 [2] => 0.002 [3] => -23.9
explanation
our regex+|(?=-)
. split on whatever matches it matches +
, or |
... the lookahead (?=-)
matches position next character -
, allowing maintain -
then split! option 2 if decide want maintain +
character
(?=[+-])
this regex 1 lookahead asserts next position either plus or minus. sense of esthetics it's quite nice solution at. :)
output (see online demo):
[0] => 0 [1] => +1.65 [2] => +0.002 [3] => -23.9
reference
lookahead , lookbehind zero-length assertions mastering lookahead , lookbehind php regex
Comments
Post a Comment