Php regex can use digit shorthand (\d) to match a digit (0-9). To match any non digit character, regex shorthand \D (uppercase backslash D) can be used.
\d | Any digit (0-9) |
\D | Any character other than 0-9 |
preg_match – check if a string contains only digit characters
<?php if (preg_match('/^\d*$/i', "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: 123 (at offset 0)
Env: PHP version 7.4.33 (Linux)
preg_replace – remove non digit characters from a string
<?php $str = "Remove non digits 123"; $newstr = preg_replace('/\D/', "", $str, -1, $count); if ($count > 0) { echo "newstr after $count replacement(s):\n$newstr\n"; } else { echo "No replacement\n"; } ?>
newstr after 18 replacement(s): 123
Env: PHP version 7.4.33 (Linux)