How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

October 26, 2018

There are a couple of ways to achieve this, both very simple.

The most simple is to use ctype_alnum(). This function has been in PHP since PHP4. The following code would output 'all passed', as all three strings are alphanumeric

<?php
if( ctype_alnum("aBcDeFg1234") &&  ctype_alnum("aaa") &&  ctype_alnum("123") ) {
  echo "all passed";
}

If you need a bit more flexibility, then you could use regex:

<?php
return preg_match('/[^a-z0-9]/i', $input);

In the example above, it adds no real advantage and is slower than ctype_alnum so I would recommend just using ctype_alnum.

If you need to check if alpha numeric, but include underscores and dash (hyphen), then you can use the following regex check:

<?php
if(preg_match('/[^a-z_\-0-9]/i', $input))
{
    // $input was alpha numeric with underscores
    return true;
}
    return false;

//(or just return preg_match(...)

(Both of these are case insensitive, thanks to the i modifier)

You could also do this:

<?php
preg_match('/^[\w-]+$/',$input)

Or even [:alnum:]

<?php
preg_match("/[^[:alnum:]\-_]/",$str)