How to usestrpbrk Function in PHP
The strpbrk function searches a string for any of a set of characters. It returns a string starting from the first occurrence of any of the specified characters in the given string. If none of the characters are found, it returns false.
Example: In this example, we will use the strpbrk function to check if the given string contains any special characters.
<?php
function specialChars($str) {
$specialChars = '!@#$%^&*()-_=+[{]};:\'",<.>/?\\|';
return strpbrk($str, $specialChars) !== false;
}
$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