简体   繁体   中英

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.

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

Just a trivial regex would do it:

$nums = preg_replace("/\D/","",$input);

Ideally you should save it as that and only format it in the output, which would be done like this:

$output = preg_replace("/(...)(...)(....)/","$1-$2-$3",$nums);

Something like this would work (stolen from How do you format a 10 digit string into a phone number? )

$phone = preg_replace("/[^0-9]/", "", $phone);
echo "(".substr($phone, 0, 3).") ".substr($phone, 3, 3)."-".substr($phone,6);

Here's a regex for a 7 or 10 digit number, with extensions allowed, delimiters are spaces, dashes, or periods:

^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$

Or you could use the sledgehammer approach: just strip out anything non-numeric and format to your heart's content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM