php-regexHow to use PHP regex to match special characters?
PHP regex can be used to match special characters using the preg_match()
function.
$string = 'This is a string with special characters!';
if (preg_match('/[^a-zA-Z0-9\s]/', $string)) {
echo 'Special characters found!';
}
Output example
Special characters found!
The code above uses the preg_match()
function to check if the string contains any special characters. The regex pattern /[^a-zA-Z0-9\s]/
is used to match any character that is not a letter, number, or whitespace.
preg_match()
: a PHP function used to match a regex pattern against a string/[^a-zA-Z0-9\s]/
: a regex pattern used to match any character that is not a letter, number, or whitespace
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match a zip code?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match a year?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match an XML tag?
- How to use PHP regex to match whitespace?
See more codes...