views:

212

answers:

4

I have an input for users where they are supposed to enter their phone number. The problem is that some people write their phone number with hyphens and spaces in them. I want to put the input trough a filter to remove such things and store only digits in my database.

I figured that I could do some str_replace() for the whitespaces and special chars. However I think that a better approach would be to pick out just the digits instead of removing everything else. I think that I have heard the term "whitelisting" about this.

Could you please point me in the direction of solving this in PHP?

Example: I want the input "0333 452-123-4" to result in "03334521234"

Thanks!

+3  A: 

This is a non-trivial problem because there are lots of colloquialisms and regional differences. Please refer to What is the best way for converting phone numbers into international format (E.164) using Java? It's Java but the same rules apply.

I would say that unless you need something more fully-featured, keep it simple. Create a list of valid regular expressions and check the input against each until you find a match.

If you want it really simple, simply remove non-digits:

$phone = preg_replace('![^\d]+!', '', $phone);

By the way, just picking out the digits is, by definition, the same as removing everything else. If you mean something different you may want to rephrase that.

cletus
Nicely explained. +1
Boldewyn
Your example code did work very well but I had a real hard time trying to understand it. I wrote:$phone = preg_replace('/[^\d]/', '', $phone);instead. Is there a difference between these two? Where can I read more about the exclamation marks you use?
nibbo
The only difference is that I'm replacing a group of non-digits with an empty string (hence the + operator to indicate one or more) rather than a single non-digit with an empty string. Very minor difference really.
cletus
+1  A: 
$number = filter_var(str_replace(array("+","-"), '', $number), FILTER_SANITIZE_NUMBER_INT);

Filter_Var removes everything but pluses and minuses, and str_replace gets rid of those.

or you could use preg_replace

$number = preg_replace('/[^0-9]/', '', $number);
Chacha102
A: 

You could do it two ways. Iterate through each index in the string, and run is_numeric() on it, or you could use a regular expression on the string.

contagious
A: 

On the client side I do recommand using some formating that you design when creating a form. This is good for zip or telephone fields. Take a look at this jquery plugin for a reference. It will much easy later on the server side.

Elzo Valugi