How to check whether every character is alpha-numeric in PHP?

15,699

Solution 1

It's probably a better idea to use the builtin functions: ctype_alnum

Solution 2

preg_match("/^[A-Za-z0-9]*$/", $new_password);

This gives true if all characters are alphanumeric (but beware of non-english characters). ^ marks the start of the string, and ^$^ marks the end. It also gives true if the string is empty. If you require that the string not be empty, you can use the + quantifier instead of *:

preg_match("/^[A-Za-z0-9]+$/", $new_password);

Solution 3

Old question, but 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;
}
?>
Share:
15,699
wamp
Author by

wamp

Updated on June 09, 2022

Comments

  • wamp
    wamp almost 2 years
    preg_match_all("/[^A-Za-z0-9]/",$new_password,$out);
    

    The above only checks the 1st character, how to check whether all are alpha-numeric?