preg_match and ereg


I tried the following two functions to check if a variable is numeric or not. The first function gave me a negative result.


$myvar = 123;
echo  "Amount Should be Numeric.";
echo "Amount is numeric";

But the second function worked.

$myvar = 123;
echo "Amount Should be Numeric.";
echo "Amount is numeric";

I could not understand the mystery behind it.

Can you explain plz?


POSIX uses different character classes than PCRE. You would have to replace the \d by its corresponding POSIX class:

$myvar = 123;
  echo  "Amount Should be Numeric.";
  echo "Amount is numeric";

   Within  a bracket expression, the name of a character class enclosed in
   `[:' and `:]' stands for the list of all characters belonging  to  that
   class.  Standard character class names are:

          alnum       digit       punct
          alpha       graph       space
          blank       lower       upper
          cntrl       print       xdigit

   These  stand  for the character classes defined in wctype(3).  A locale
   may provide others.  A character class may not be used as  an  endpoint
   of a range.

Why not just use php’s is_numeric() ?


I am not looking for an alternate solution. I just wanna know what the mys try is…


If you do this you will see what results they give you. Another one gives true and another false. That is why you get such a result. You can see both functions return values from what they should be in what situation.


But shouldn’t it both return true logically?

As far as I’m aware the ereg and preg engines are different, are you sure the same pattern is valid in both?

Well not sure. Is that what is causing it?

According to that latter preg_match should return either the number of times pattern matches or false if error occured. So it seems that in your pattern there must be an error then right? I dont really know what that error would be now.

And preg_match uses perl compatible regular expressions which ereg does not. So maybe it has something to do with this?

ereg meh don’t bother using it. Stick with the preg functions.
For this you should really use is_numeric, however.

$v = '4.550';
var_dump( preg_match( '/^(?:\\d+(?:\\.\\d+)?|\\.\\d+)$/', $v ) );

k thanx guys for your replies.

Probably. Using the perl compatible version is recommended, it supports more things, and is more ‘universal’, and supposedly faster.

Nevermind… :slight_smile:

Old thread I know, but wanted to know what are “posix”?

Many thanks

regarding preg_match vs ereg, there is no doubt to use preg_match.
Quoted from PHP Manual(about ereg):

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

dude … you really should read threads (or at least last post) before replying