sortof
sortof

Reputation: 540

How to split math operators from numbers in a string

Im trying to split between operators and float/int values in a string.

Example:

$input = ">=2.54"; 

Output should be:

array(0=>">=",1=>"2.54"); .

Operators cases : >,>=,<,<=,=

I tried something like this:

$input = '0.2>';
$exploded = preg_split('/[0-9]+\./', $input);

but its not working.

Upvotes: 1

Views: 170

Answers (3)

The fourth bird
The fourth bird

Reputation: 163217

If you want to split between the operators, you might use and alternation to match the variations of the operators, and use \K to reset the starting point of the reported match.

This will give you the position to split on. Then assert using lookarounds that there is a digit on the left or on the right.

\d\K(?=[<>=])|(?:>=?|<=?|=)\K(?=\d)

Explanation

  • \d\K(?=[<>=]) Match a digit, forget what was matched and assert either <, > or = on the right
  • | Or
  • (?:>=?|<=?|=)\K(?=\d) Match an operator, forget what was matched and assert a digit on the right

Regex demo | Php demo

For example

$strings = [
    ">=2.54",
    "=5",
    "0.2>"
];

$pattern = '/\d\K(?=[<>=])|(?:>=?|<=?|=)\K(?=\d)/';

foreach ($strings as $string) {
    print_r(preg_split($pattern, $string));
}

Output

Array
(
    [0] => >=
    [1] => 2.54
)
Array
(
    [0] => =
    [1] => 5
)
Array
(
    [0] => 0.2
    [1] => >
)

Upvotes: 1

Illya
Illya

Reputation: 1275

Try :

$input = ">=2.54";
preg_match("/([<>]?=?) ?(\d*(?:\.\d+)?)/",$input,$exploded);

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520978

Here is a working version using preg_split:

$input = ">=2.54";
$parts = preg_split("/(?<=[\d.])(?=[^\d.])|(?<=[^\d.])(?=[\d.])/", $input);
print_r($parts);

This prints:

Array
(
    [0] => >=
    [1] => 2.54
)

Here is an explanation of the regex used, which says to split when:

(?<=[\d.])(?=[^\d.])  a digit/dot precedes and a non digit/dot follows
|                     OR
(?<=[^\d.])(?=[\d.])  a non digit/dot precedes and a digit/dot follows

That is, we split at the interface between a number, possibly a decimal, and an arithmetic symbol.

Upvotes: 1

Related Questions