开发者

RegEx for Phone Number Numbers with Letters

开发者 https://www.devze.com 2023-02-17 19:30 出处:网络
I need to format a phone number as one long string of numbers (US Phone Number format) // I know there are tons more

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 CAL开发者_如何学JAVAL NOW to:

18002255669


To save some typing...

$phoneNumber = strtr($phoneLetters, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "22233344455566677778889999");


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");


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号