PHP regular expression - filter number only
To remove anything that is not a number:
$output = preg_replace('/[^0-9]/', '', $input);
Explanation:
[0-9]
matches any number between 0 and 9 inclusively.^
negates a[]
pattern.- So,
[^0-9]
matches anything that is not a number, and since we're usingpreg_replace
, they will be replaced by nothing''
(second argument ofpreg_replace
).
Using is_numeric or intval is likely the best way to validate a number here, but to answer your question you could try using preg_replace instead. This example removes all non-numeric characters:
$output = preg_replace( '/[^0-9]/', '', $string );