有很多更有效的方法可以做到这一点,并且以下代码的内存使用并不完美(修改传入参数),但是如果您想在不使用正则表达式的情况下遵循逻辑,这将起作用(注意不处理 13 或 1800 个数字,但如果您也需要这些数字,这很容易解决):
function fmtAusPhoneNum($phoneNum) {
// First strip spaces and non numerics
$phoneNum = preg_replace('/\D+/', '', $phoneNum);
// Strip AUS international access code
if (substr($phoneNum, 0, 4) == '0011') {
$phoneNum = substr($phoneNum, 4, strlen($phoneNum) - 4);
}
// Strip UK (and some others) international code
if (substr($phoneNum, 0, 2) == '00') {
$phoneNum = substr($phoneNum, 2, strlen($phoneNum) - 2);
}
// Add any other international prefixes here.
// If first 2 digits are '61' then international format, take off 2
if (substr($phoneNum, 0, 2) == '61') {
$phoneNum = substr($phoneNum, 2, strlen($phoneNum) - 2);
}
// If STD 0 code, take it off.
elseif (substr($phoneNum, 0, 1) == '0') {
$phoneNum = substr($phoneNum, 1, strlen($phoneNum) - 1);
}
// Now should have a 9 char long digit.
if (strlen($phoneNum)!=9) {
echo "Warning: can't parse Australian number - less access codes, should have 9 digits only\n";
}
// If first digit is 4, it's a mobile, format 04xx xxx xxx
if (substr($phoneNum, 0, 1) == '4') {
$phoneNum = '0' . substr($phoneNum, 0, 3) . ' ' . substr($phoneNum, 3, 3) . ' ' . substr($phoneNum, 6, 3);
} else {
// It's a landline number, split into area code eg 03 and 2 lots of 4 digits
$phoneNum = '0' . substr($phoneNum, 0, 1) . ' ' . substr($phoneNum, 1, 4) . ' ' . substr($phoneNum, 5, 4);
}
return $phoneNum;
}
// Test it
echo fmtAusPhoneNum('0061 421 123 123') . "\n";
echo fmtAusPhoneNum('0421741940') . "\n";
echo fmtAusPhoneNum('+61421741940') . "\n";
echo fmtAusPhoneNum('61394190231') . "\n";
echo fmtAusPhoneNum('03 5521 7475') . "\n";