Search code examples
phpmysqlstringintegerreformatting

PHP to strip not integers and reformat the output as phone number


I am trying to make a way that phone numbers being inserted into the database all go in following the same convention regardless of how they are inserted.

so (123) 456.7890 and 123.456.7890

would both end up going into the database as 123-456-7890

Im thinking there has to be a function that will allow me to strip all non Integer characters so 123.456.7890 could be turned into 1234567890 and then reformat it as xxx-xxx-xxxx

Perhaps im wrong about this but im thinking php has to have a way of accomplishing something along these lines so any help would be greatly appreciated.


Solution

  • // Remove any non-number character
    $str = preg_replace('/[^\d]/', '', $str);
    // Insert dashes
    $str = preg_replace('/(\d)(?=(\d{4}|\d{7})$)/', '$1-', $str);
    

    Here's the fiddle: http://codepad.viper-7.com/pQlwVw