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 match a space using PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a zip code?
- How to get the first match when using regex in PHP?
- How to match the end of a string when using regex in PHP?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match special characters?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match UUID?
- How to match strings starting with a certain string using PHP regex?
See more codes...