I have a string variable in php, with look like "0+1.65+0.002-23.9
", and I want to split in their individual values.
Ex:
0
1.65
0.002
-23.9
I Try to do with:
$keys = preg_split("/^[+-]?\\d+(\\.\\d+)?$/", $data);
but not work I expected.
Can anyone help me out? Thanks a 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
+|(?=-)
. We will split on whatever it matches+
, OR |
...(?=-)
matches a position where the next character is a -
, allowing us to keep the -
Option 2 if you decide you also want to keep the +
Character
(?=[+-])
This regex is one lookahead that asserts that the next position is either a plus or a minus. For my sense of esthetics it's quite a nice solution to look at. :)
Output (see online demo):
[0] => 0
[1] => +1.65
[2] => +0.002
[3] => -23.9
Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With