Tomer
Tomer

Reputation: 17930

how to use preg_replace to extract negative-positive numbers from a string?

I have a string like this:

SELECT NOW(),DATE_ADD(NOW(), INTERVAL -11 day)

and I need to get the number which can be positive or negative.

I tried using:

preg_replace("/^-?[0-9]/", '', $str);

but it doesn't seem to work.

Upvotes: 0

Views: 1975

Answers (1)

nachito
nachito

Reputation: 7035

If you want to "extract" the number from the string, and not manipulate it then preg_match() is what you should be using. If you want to remove numbers from a string then just remove the ^ from your regex which is restricting your regex to match the beginning of the string.

Regex:

/-?[0-9]+/  -- note that the + matches 1 or more numbers

preg_match syntax:

preg_match('/-?[0-9]+/', $str, $match);

Upvotes: 3

Related Questions