Hello Friends Today, through this tutorial, I will tell you How do you Validate Check if a String Contains Only Alphanumeric Characters in PHP With Example? You can use a regular expression to check if a string contains only alphanumeric characters in PHP. Here’s an example:
<?php // Function to check if a string contains only alphanumeric characters function isAlphaNumeric($str) { return preg_match('/^[a-zA-Z0-9]+$/', $str); } // Example usage $string1 = "Hello123"; $string2 = "Hello123!"; // Contains non-alphanumeric character if (isAlphaNumeric($string1)) { echo "$string1 contains only alphanumeric characters.\n"; } else { echo "$string1 contains non-alphanumeric characters.\n"; } if (isAlphaNumeric($string2)) { echo "$string2 contains only alphanumeric characters.\n"; } else { echo "$string2 contains non-alphanumeric characters.\n"; } ?>
Output:
Hello123 contains only alphanumeric characters. Hello123! contains non-alphanumeric characters.
In this example, the `isAlphaNumeric()` function takes a string as input and uses `preg_match()` to check if the string contains only alphanumeric characters. The regular expression `/^[a-zA-Z0-9]+$/` matches strings that consist entirely of one or more alphanumeric characters.