How to check if a string contains only letters and numbers using RegEx in PHP

1 Answer

0 votes
function isAlphanumeric($str) {
    // Define the regular expression for alphanumeric characters
    $alphanumericRegex = '/^[a-zA-Z0-9]+$/';

    // Use preg_match to check if the string matches the pattern
    return preg_match($alphanumericRegex, $str) === 1;
}

$str = "VuZ3q7J4wo35Pi";

if (isAlphanumeric($str)) {
    echo "The string contains only letters and numbers.\n";
} else {
    echo "The string contains characters other than letters and numbers.\n";
}


  
/*
run:
      
The string contains only letters and numbers.

*/

 



answered Mar 26 by avibootz
...