Is there a Php function to determine if a string consist of only ASCII alphanumerical characters?
Note: I'm sorry if the question sounds dumb to some, but I couldn't easily find such a function in the Php manual.
Try ctype_alnum
preg_match('/^[a-z0-9]+$/i', $str);
Edit: John T's answer is better. Just providing another method.
This is my solution
<?php
public function alphanum($string){
if(function_exists('ctype_alnum')){
$return = ctype_alnum($string);
}else{
$return = preg_match('/^[a-z0-9]+$/i', $string) > 0;
}
return $return;
}
?>
My long, but simple solution
strspn($string, '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM_') == strlen($string)
Function strspn() finds the length of the initial segment of $string that contains only letters, numbers and underscore character (second argument). If entire string consists only of letters, numbers and underscore, the returned value will be equeal to the length of the string.