Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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.

like image 733
Gopar Avatar asked Jan 11 '23 08:01

Gopar


1 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 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

  • Lookahead and Lookbehind Zero-Length Assertions
  • Mastering Lookahead and Lookbehind
like image 177
zx81 Avatar answered Jan 24 '23 23:01

zx81