Search code examples
phpuser-inputwhitelist

Whitelist in php


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!


Solution

  • 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.