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
webdevetc

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



More...


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 show a specific view file for certain error codes?

How to review blog posts (written by other users) before they get published on your WordPress blog?

How to sort an array in javascript?

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

How to hide certain file types from directory listings

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

A list of operators on Eloquent's where() method

How to block IPv6 IP addresses in .htaccess

What is the loop variable in a @foreach loop in Blade?

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