Php regex can use word shorthand \w (lowercase backslash w) to match a word character. It matches with any of the following:
- letters (a-z,A-Z)
- Numbers (0-9)
- Underscore (_)
To match any non word character, regex shorthand \W (uppercase backslash W) can be used.
preg_match – check if a string contains only word characters
<?php
if (preg_match('/^\w*$/i', "Only_word_characters_123", $matches, PREG_OFFSET_CAPTURE)) {
echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";
} else {
echo "No match\n";
}
?>matched string: Only_word_characters_123 (at offset 0)
Env: PHP version 8.2.29 (Linux)
preg_replace – remove non word characters from a string
<?php
$str = "Remove non word_characters like + and_keep 123";
$newstr = preg_replace('/\W/', "", $str, -1, $count);
if ($count > 0) {
echo "newstr after $count replacement(s):\n$newstr\n";
} else {
echo "No replacement\n";
}
?>newstr after 7 replacement(s): Removenonword_characterslikeand_keep123
Env: PHP version 8.2.29 (Linux)