Click to See Complete Forum and Search --> : PREG_MATCH for numbers only


markos
11-05-2007, 01:23 AM
I've used PHP for a few years (self taught), but rarely touched regular expression. It's something I now feel I should tackle.

I've got the following:-

if ($price[1]) {
if (preg_match('/^[0-9]{1,}/', $price[1])) {
echo $price[1] . " is numeric";
} else {
echo $price[1] . " is NOT numeric";
}
}

And when I try it out I get:-

1 = "1 is numeric"
a = "a is NOT numeric"

So far so good, but...

1a1 = "1a1 is numeric"

Which is obviously wrong.

I'm reading the script as if it says it should match up with 1 or more numbers (i.e. 0 through 9), and if it does to echo the "numeric" response, otherwise the "NOT numeric" response. I can't understand why it fails to correctly identify 1a1 as NOT numeric. Can anyone enlighten me?

bokeh
11-05-2007, 01:56 AM
preg_match('/^[0-9]{1,}$/', $price[1])

markos
11-05-2007, 02:01 AM
Ahhhh.... right.

Yes, I see it now. The "$" signifies the end of the string, so before as long as it started with a numeric (^[0-9]) it was going to validate as a numeric. But now, with the "$" in there it's saying it has to match from the start to the end of string.

Thanks mate.

NogDog
11-05-2007, 03:19 AM
Just FYI, you could abbreviate it down to:

preg_match('/^\d+$/', $price[1])


Simpler and probably quicker, though of no use if the purpose is just to learn regular expressions:

if(ctype_digit($price[1]))
{
// it contains only digits
}
else
{
// it contains something other than a digit or is empty
}

markos
11-05-2007, 03:47 AM
So \d equates to 'digits'? :) Cool, thanks.

What should I be Googling for to see a list of other "\values" ? Is there a name for this?

NogDog
11-05-2007, 04:02 AM
The PHP.net manual page for PCRE syntax (http://us3.php.net/manual/en/reference.pcre.pattern.syntax.php)

On this page, they refer that particular type of thing as "generic character type" under the "Backslash" heading.

markos
11-05-2007, 04:05 AM
Lovely job, thanks :)

Shivaraj
12-14-2011, 06:41 AM
[QUOTE=NogDog;821278]Just FYI, you could abbreviate it down to:

preg_match('/^\d+$/', $price[1])

Thank you...i used it

007Julien
12-14-2011, 04:50 PM
It is not going to work with 5 $ (or 5 Euros), 4.19 £ or 6.49 $ or 59,769.20 Indonesian Rupiah (Euro foreign exchange reference rates as at 14 December 2011). You have probably to take all the number point and comma (to remove after) from the beginning of the string !