Gopar
Gopar

Reputation: 43

How to split negative and positive values in string using php?

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.

Upvotes: 4

Views: 393

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94642

You could try this

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

print_r($ta);

Which gives you an array containing each field like so:

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

RE: Your comment: The originals values are in a string variable only separated for a sign possitive or negative

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

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

which gives a similiar answer but with the correct inputs and outputs

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

Upvotes: 4

zx81
zx81

Reputation: 41838

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 is +|(?=-). We will split on whatever it matches
  • It matches +, OR |...
  • the lookahead (?=-) matches a position where the next character is a -, allowing us to keep the -
  • Then we split!

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

Upvotes: 5

Related Questions