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

What is the spaceship operator (<=>) in PHP?

What is Agile software development?

What are route patterns in Laravel?

How to force gzip compression in Apache with .htaccess

How to check if a object has a static variable defined?

How to exclude URLs from the Laravel CSRF protection?

How do Invokable Controllers work in Laravel?

Push vs Pop vs Shift vs Unshift

How to order a Laravel hasMany relationship?

How to add the default charset to UTF-8 in .htaccess