How to usectype_alnum() Function in PHP
Another method to check for special characters in a string is by using the ctype_alnum() function, which checks if all characters in a string are alphanumeric (letters and numbers). the specialChars() function uses the ctype_alnum() function to check if the input string is alphanumeric. If the string is not alphanumeric, it means that it contains special characters. The function returns true if special characters are found and false otherwise.
Example: This example shows if any special character present in the given string or not using ctype_alnum() Function.
<?php
function specialChars($str) {
return !ctype_alnum($str);
}
$str = "Hello@Geeks";
if (specialChars($str)) {
echo "String contain special characters.";
} else {
echo "String does not contain special characters.";
}
?>
Output
String contain special characters.
PHP to Check if a String Contains any Special Character
Given a String, the task is to check whether a string contains any special characters in PHP. Special characters are characters that are not letters or numbers, such as punctuation marks, symbols, and whitespace characters.
Examples:
Input: str = "Hello@Geeks"
Output: String contain special characters.
Input: str = "w3wiki"
Output: String does not contain special characters.
These are the following approaches:
Table of Content
- Approach 1: Using Regular Expressions
- Approach 2: Using ctype_alnum() Function
- Approach 3: Using strpbrk Function
Contact Us