RegEx for Phone Number Numbers with Letters

本小妞迷上赌 提交于 2020-01-04 10:52:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!