Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Character Type Functions : ctype_alnum

ctype_alnum

Check for alphanumeric character(s) (PHP 4 >= 4.0.4, PHP 5)
bool ctype_alnum ( string text )

Example 416. A ctype_alnum() example (using the default locale)

<?php
$strings
= array('AbCd1zyZ9', 'foo!#$bar');
foreach (
$strings as $testcase) {
   if (
ctype_alnum($testcase)) {
       echo
"The string $testcase consists of all letters or digits.\n";
   } else {
       echo
"The string $testcase does not consist of all letters or digits.\n";
   }
}
?>

The above example will output:

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

Code Examples / Notes » ctype_alnum

raj

When checking strings with multiple words for non alphanumeric characters ctype_alnum would consider space as non alphanumeric character as well.
So to check a string with multiple words for non alphanumeric characters use str_replace
foreach ($imported_queries as $check_aplhanum) {
   $check_aplhanum = str_replace (" ", "", $check_aplhanum);
   if (!(ctype_alnum($check_aplhanum))) {
       echo "Query string contains alphanumeric characters";
   }
}


sinured

Caution: ctype_alnum() will return false on integers.
<?php
var_dump(ctype_alnum('3')); // true
var_dump(ctype_alnum(3)); // false
?>
See http://bugs.php.net/bug.php?id=42007 .


mvanberkel

Although in an empty string "every character is either a letter or a digit", ctype_alnum('') will return bool(false)!
Please try at home :-)
For now, I use:
if($input !== '' && !ctype_alnum($input))
  throw new Exception('Invalid input');
Somebody better suggestions? (except preg_match)


Change Language


Follow Navioo On Twitter
ctype_alnum
ctype_alpha
ctype_cntrl
ctype_digit
ctype_graph
ctype_lower
ctype_print
ctype_punct
ctype_space
ctype_upper
ctype_xdigit
eXTReMe Tracker