Php function to determine if a string consists of only alphanumeric characters?

Is there a Php function to determine if a string consists of only alphanumeric ASCII characters?

Note. Sorry if the question sounds silly to some, but I could not easily find such a feature in the Php manual.

+2
source share
4 answers
+9
source
preg_match('/^[a-z0-9]+$/i', $str);

Edit: John T's answer is better. Just providing another method.

+1
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

,

strspn($string, '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM_') == strlen($string)

The strspn () function finds the length of the initial segment of the string $, which contains only letters, numbers, and the underscore (second argument). If the whole string consists only of letters, numbers, and underscores, the return value will be equal to the length of the string.

0
source

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


All Articles