How to separate negative and positive values ​​in a string using php?

I have a string variable in php that looks like " 0+1.65+0.002-23.9" and I want to separate their individual values.

Example:

 0
1.65
0.002
-23.9

I am trying to do with:

$keys = preg_split("/^[+-]?\\d+(\\.\\d+)?$/", $data);

but I did not expect work.

Can anyone help me out? Thank you very much in advance.

+4
source share
2 answers

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 regular expression +|(?=-). We will share everything so that it does not correspond.
  • It matches +, OR |...
  • lookahead (?=-)matches the position where the next character is - -, which allows us to save-
  • !

2, , +

(?=[+-])

- , , , . .:)

(. -):

[0] => 0 
[1] => +1.65
[2] => +0.002
[3] => -23.9

+5

$data = ' 0 1.65 0.002 -23.9';
$t = str_replace( array(' ', ' -'), array(',',',-'), trim($data) );
$ta = explode(',', $t);

print_r($ta);

, , :

Array
(
    [0] => 0
    [1] => 1.65
    [2] => 0.002
    [3] => -23.9
)

RE: : ,

$data = ' 0+1.65+0.002-23.9 ';

$t = str_replace( array('-', '+'), array(',-',',+'), trim($data) );
$ta = explode(',', $t);
print_r($ta);

,

Array
(
    [0] => 0
    [1] => +1.65
    [2] => +0.002
    [3] => -23.9
)
+4

Source: https://habr.com/ru/post/1546127/


All Articles