php-regexHow to use PHP regex to match a non-word?
Using PHP regex to match a non-word is possible with the \W
character class. This character class matches any non-word character, which includes any character that is not a letter, number, or underscore.
Example code
$string = 'This is a string!';
$pattern = '/\W/';
preg_match_all($pattern, $string, $matches);
print_r($matches);
Output example
Array
(
[0] => Array
(
[0] =>
[1] =>
[2] => !
)
)
Code explanation
$string
: This is the string that we are searching through.$pattern
: This is the regular expression pattern that we are using to search for non-word characters.preg_match_all()
: This is the PHP function that we are using to search for matches in the string.$matches
: This is the array that will contain all of the matches that are found.print_r()
: This is the PHP function that we are using to print out the contents of the$matches
array.
Helpful links
More of Php Regex
- How to use PHP regex to match an exact string?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match a hashtag?
- How to use PHP regex to match URL path?
- How to use quantifiers in PHP regex?
- How to use PHP regex to match whitespace?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match UUID?
- How to use an "or" condition in PHP regex?
- How to use capture group in PHP regex?
See more codes...