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

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

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

  1.             if( ctype_alnum("aBcDeFg1234") &&  ctype_alnum("aaa") &&  ctype_alnum("123") ) {
  2.               echo "all passed";
  3.             }

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

  1. 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:

  1. if(preg_match('/[^a-z_\-0-9]/i', $input))
  2. {
  3. return true;
  4. }
  5. return false;

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

You could also do this:

  1. preg_match('/^[\w-]+$/',$input)

Or even [:alnum:]

  1. preg_match("/[^[:alnum:]\-_]/",$str)

webdevetc profile pic

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This ( is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.


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

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to use Anonymous classes in PHP 7?

How to prevent Eloquent from adding created_at or updated_at timestamps?

How to find out which php.ini file PHP is using?

How to find the index of a value in an array in JS?

301 Redirect a single URL in .htaccess to a new location

How to select all rows for a certain month (or day, year or time), using Eloquent

How to get the last character of a string in JS?

How to find an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to convert a string to an array of it's characters in PHP?

How to set up an alias to map one directory to another destination