Doug
Doug

Reputation: 83

PHP Regular Expression Ignore Negative Numbers in String

I've looked all over the place, but I can't seem to only return the first positive, real number. So far, I have successfully found how to find the first positive or negative number and also only find the first negative number. Below are the two I did correctly and the one I can't get.

$str1 = "-ABS-.-179.3333es-k15dk825.44f";
  1. Find first real number in string:

    preg_match("/-?((.\d+)|(\d+(.\d+)?))/", $str1, $matches) // <- GOOD! Expected output: -179.3333 Actual output: -179.3333

  2. Find first, negative real number in string:

    preg_match("/-((.\d+)|(\d+(.\d+)?))/", $str1, $matches) // <- GOOD! Expected output: -179.3333 Actual output: -179.3333

  3. Find first, positive real number in string:

    preg_match("/(?<!-)((.\d+)|(\d+(.\d+)?))/", $str1, $matches) //<- WRONG! Expected output: 15 Actual output: 79.3333

Upvotes: 2

Views: 449

Answers (2)

donatJ
donatJ

Reputation: 3364

I think you're looking for:

preg_match('/(?<!-|\d|\.)\d+/', $str1, $matches);

Update

How's about:

preg_match('/(?<!-|\d|\.)\d+(\.\d+)?/', $str1, $regs);

Upvotes: 2

Vlam
Vlam

Reputation: 1798

Try the following and see if it does what you want.

preg_match_all('/[^\-\d\.]((?:\d+)(?:(?:\.\d+)|(?:\d+)))/', $str1, $matches);

var_dump($matches[1]);

Upvotes: 1

Related Questions