I'm trying to remove everything from a string but just numbers (0-9).
I thought this would work..
echo preg_replace("[^0-9]","",'604-619-5135');
But it echos "604-619-5135". What am I missing???
Join Stack Overflow to learn, share knowledge, and build your career.
I'm trying to remove everything from a string but just numbers (0-9).
I thought this would work..
echo preg_replace("[^0-9]","",'604-619-5135');
But it echos "604-619-5135". What am I missing???
Try this:
preg_replace('/[^0-9]/', '', '604-619-5135');
preg_replace uses PCREs which generally start and end with a /
.
(?flags)
) the people who designed/wrote the function/API thought it was a good idea to pass the regex flags with the double quoted /flags
form instead of using an extra function parameter.
– Qtax
Jul 7 '11 at 0:28
This is for future developers, you can also try this. Simple too
echo preg_replace('/\D/', '', '604-619-5135');
You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:
echo preg_replace("/[^0-9]/","",'604-619-5135');
a much more practical way for those who do not want to use regex:
$data = filter_var($data, FILTER_SANITIZE_NUMBER_INT);
note: it works with phone numbers too.
FILTER_SANITIZE_NUMBER_INT
leaves plus +
and minus -
signs, not only digits.
– Qrzysio
Aug 4 '20 at 19:45