Remove all non-numeric characters from a string; [^0-9] doesn't match as expected

PhpRegexStringPhone NumberSanitization

Php Problem Overview


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???

Php Solutions


Solution 1 - Php

Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.

Solution 2 - Php

This is for future developers, you can also try this. Simple too

echo preg_replace('/\D/', '', '604-619-5135');

Solution 3 - Php

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');

Solution 4 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjeffkeeView Question on Stackoverflow
Solution 1 - PhpChris EberleView Answer on Stackoverflow
Solution 2 - PhpNavneil NaickerView Answer on Stackoverflow
Solution 3 - PhpSBerg413View Answer on Stackoverflow
Solution 4 - PhpAlp AltunelView Answer on Stackoverflow