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 convert a PHP regex to JavaScript regex?
- How to use PHP regex to match an exact string?
- How to match a double quote in PHP regex?
- How to use named capture groups in PHP regex?
- How to use PHP regex to match URL path?
- How to match a space using PHP regex?
- How to use an "or" condition in PHP regex?
- How to get last matched occurrence in PHP regex?
See more codes...