preg_match and ereg

Discussion in 'PHP' started by cancer10, Nov 28, 2008.

  1. #1
    Hi,

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

    
    <?php
    
    $myvar = 123;
    if(!ereg("^[\d]*\.?\d*$",$myvar))
    echo  "Amount Should be Numeric.";
    else
    echo "Amount is numeric";
    ?>
    PHP:
    But the second function worked.
    
    <?php
    $myvar = 123;
    if(!preg_match("/^[\d]*\.?\d*$/",$myvar))
    echo "Amount Should be Numeric.";
    else
    echo "Amount is numeric";
    ?>
    PHP:

    I could not understand the mystery behind it.

    Can you explain plz?


    Thanx
     
    cancer10, Nov 28, 2008 IP
  2. peeeev

    peeeev Peon

    Messages:
    36
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    ereg uses POSIX.2 regular expressions syntax, so there is no "\d" there. Use "[[:digit:]]" insted of "\d"
    So, this is correct code:
    if(!ereg("^[[:digit:]]*\.?[[:digit:]]*$",$myvar))
    PHP:
     
    peeeev, Nov 28, 2008 IP
  3. cancer10

    cancer10 Guest

    Messages:
    364
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    k thanx for the info.
     
    cancer10, Nov 28, 2008 IP
  4. misbah

    misbah Active Member

    Messages:
    265
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    68
    #4
    or... you can use this
    if (is_numeric($test)) {
    echo "this variable is numeric
    }
    
    PHP:
     
    misbah, Nov 28, 2008 IP