How to use preg_match to validate variables?

Discussion in 'PHP' started by Jay-S, Feb 17, 2010.

  1. #1
    Hello,

    I have used preg_match in the past to validate a variable by check that it only has numbers and letters. The problem is that I not longer remember what the code was.

    Does any one know how to use preg_match to only allow numbers and letters in the variable?

    Thanks!
    Jay S.
     
    Jay-S, Feb 17, 2010 IP
  2. systematical

    systematical Peon

    Messages:
    81
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    All you need is here http://php.net/manual/en/function.preg-match.php
     
    systematical, Feb 17, 2010 IP
  3. koko5

    koko5 Active Member

    Messages:
    394
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    70
    #3
    Better using ctype_alnum in this case.

    p.p.:
    
    if (preg_match('#^\w+$#us',$string)) echo $string." consists of all letters or digits";
    
    Code (markup):
     
    koko5, Feb 18, 2010 IP
  4. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #4
    \w also includes underscores.
     
    SmallPotatoes, Feb 18, 2010 IP
  5. koko5

    koko5 Active Member

    Messages:
    394
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    70
    #5
    Thanks for remark :)
    Correct:
    if (preg_match('#^[a-z0-9]+$#ius',$string)) echo $string." consists of all letters or digits";
    PHP:
     
    koko5, Feb 18, 2010 IP