How to check if value of variable are alpha numeric

Discussion in 'PHP' started by PinoyIto, Jul 29, 2008.

  1. #1
    I am trying to test a variable if the value is alpha numeric or not.. but I don't know how..

    For example if the value of a variable is abc123 the result is true but if the value of the variable is abc@8%_ then I will get a false result..

    e.g.

    $a = "abc123";

    if($a==alphanumeric) then true

    $a = "Ab$("
    if($a==alphanumeric) then false

    I hope my question not very hard to understand :)
     
    PinoyIto, Jul 29, 2008 IP
  2. serialCoder

    serialCoder Guest

    Best Answers:
    0
    #2
    dude php have a native function for that

    ctype_alnum -- Check for alphanumeric character(s)


    so pwede mo gawin ito... (you can try this)

    if (ctype_alnum($value) )
    {
    true statement here
    }
    else
    {
    false statement here
    }
     
    serialCoder, Jul 29, 2008 IP
  3. PinoyIto

    PinoyIto Notable Member

    Messages:
    5,863
    Likes Received:
    170
    Best Answers:
    0
    Trophy Points:
    260
    #3
    cool... thanks mate will try it and will post what happened
     
    PinoyIto, Jul 29, 2008 IP
  4. yleiko

    yleiko Peon

    Messages:
    74
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    you can also use regular expression for these kind of things

    fot this specil request reg exp would be

    preg_match("/^([A-Za-z0-9]+)$/", $value)
     
    yleiko, Jul 30, 2008 IP
  5. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #5
    What yleiko said, though it's best/faster to just stick to native functions when you can. I used to use a regex expression to make sure something was all numbers and then I realized I should just be using ctype_digit().
     
    zerxer, Jul 30, 2008 IP
  6. serialCoder

    serialCoder Guest

    Best Answers:
    0
    #6
    yep, no need to reinvent the wheel when its already used by all :)
     
    serialCoder, Jul 30, 2008 IP
  7. yleiko

    yleiko Peon

    Messages:
    74
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Sure, there is no need to use reg exp when there is a native function,
    but native functions are not always enough for your needs.
    Say you need to check whether it is alphanumeric and plus some special characters (language specific characters or some other characters). You need to reg exp.
    My suggestion is for this case, use ctype_alnum function, but if you will continue coding on php (or any other language), learn reg exp. Most of the time, it saves lots of time and hundreds of coding.
     
    yleiko, Jul 30, 2008 IP