Checking a string is alphanumeric in PHP

There may be times when you need a way to check that a string only contains alpha-numeric characters. That means only alphabets A-Z nad numbers 0-9.

Most PHP-ers will probably use regular expressions and the function preg_match(). I will admit that regular expressions is really powerful, but it’s a real pain to learn and master. Fortunately PHP provides another function you can use.

Check out ctype_alnum() function.

ctype_alnum($text) will return true if $text is a mix of alphabets, numbers or both. Here’s how you can use it:

<?php
// This will return true, and print out '1'
$alphanum1 = "Eagle2008";
print ctype_alnum($alphanum1);
 
// This will return false, and print out '0'
$alphanum2 = "Eagle,2008";
print ctype_alnum($invalidUsername); // will return false
?>

Also, if you just want to look for purely alphabets, you can use the ctype_alpha(), and conversely, if you want to look for purely numbers in the string, you can use ctype_digit().

There is another function which does the same thing as ctype_digit, and that is is_numeric().

However, a better function to use in place of ctype_digit, might be is_numeric(). This example illustrates why:

<?php
 
$num1 = "2008";
print ctype_digit($num1); // This will return 1 (true)
print is_number($num1); // this will return 1 (true)
 
$num2 = 2008;
print ctype_digit($num2); // This will return 0 (false)
print is_number($num2); // this will return 1 (true)
 
$num1 = "-2008";
print ctype_digit($num2); // This will return 0 (false)
print is_number($num2); // this will return 1 (true)
?>

ctype_digit purely checks for string types, whereas is_numeric takes in multiple types of variables, such as integers, floats and strings and tries to evaluate it to have a numerical value.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
Other similar posts:


2 Responses to “Checking a string is alphanumeric in PHP”

  1. Fredrik Holmström () Says:

    is_numeric and ctype_digit don’t do the same thing…

  2. webmaster () Says:

    Thanks Fredrik.

    You’re right, is_numeric actually does more than ctype_digit.

    ctype_digit just checks for numbers making up a string and nothing more.

    is_numeric will test for integer types as well as strings, and be able to determine negative numbers.

    I’ve updated the post.

Leave a Reply

Google