问题
I need to format a phone number as one long string of numbers (US Phone Number format)
// I know there are tons more
$phones = array(
'1(800) 555-1212',
'1.800.555.1212',
'800.555.1212',
'1 800 555 1212',
'1.800 CALL NOW' // 1 800 225-5669
);
foreach($phones as $phone) {
echo "new format: ".(preg_replace("/[^0-9]/", "", $phone)."<br />\n";
}
Now this should return something like this:
8005551212 (with or without the 1)
but how do I map/convert the number with CALL NOW to:
18002255669
回答1:
You could use strtr()
.
$number = strtr($number, array('A'=> '2', 'B' => '2', ... 'Z' => '9'));
Or actually, I think:
$number = strtr($number, "AB...Z", "22...9");
回答2:
To save some typing...
$phoneNumber = strtr($phoneLetters, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "22233344455566677778889999");
回答3:
For the first step, you need to do a different regex replace (your version would now lose all the letters):
$result = preg_replace('/[^A-Z0-9]+/i', '', $phone);
Then, you need to take the string and replace each letter with its corresponding digit (see konforce's answer). That's not really a job for a regex.
来源:https://stackoverflow.com/questions/5331721/regex-for-phone-number-numbers-with-letters