How to check if each character is alpha-numeric in PHP?

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

The above only checks the 1st character, how to check if they are all alphanumeric?

+3
source share
3 answers

It is probably better to use the built-in functions: ctype_alnum

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

This gives trueif all characters are alphanumeric (but beware of non-English characters). ^denotes the beginning of a line, and ^ $ ^ denotes the end. It also gives trueif the string is empty. If you want the string not to be empty, you can use a quantifier +instead *:

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

, :

<?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;
}
?>
0

Source: https://habr.com/ru/post/1752749/


All Articles