PHP 规范化电话号码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 规范化电话号码相关的知识,希望对你有一定的参考价值。
<?php
$search_replace_mapping = array(
// country prefix normalization
'+00' => '+', '++' => '+',
// country prefix is always 00
'+' => '00',
// funny user input goulash
'i' => '1', 'I' => '1', 'l' => '1',
'o' => '0', 'O' => '0',
// ([^\diIloO\+]*)
// ...brackets
'(' => '', ')' => '',
'[' => '', ']' => '',
'[' => '', ']' => '',
// slashes
'/' => '', '\\\\' => '',
// dashes
'-' => '', '_' => '',
// whitespaces
' ' => ''
);
function normalizeTelephoneNumber($telephone_number, $search_replace_mapping) {
// fetch search and replace arrays
$search = array_keys($search_replace_mapping);
$replace = array_values($search_replace_mapping);
// simple string replacement
$telephone_number = str_replace($search, $replace, $telephone_number);
// lets kick out all dutty stuff which is left...
$telephone_number = preg_replace('~[^\d]~', '', $telephone_number);
return $telephone_number;
}
function generateSqlReplaceStatement($telephone_number, $search_replace_mapping)
{
$s = '';
$template = 'REPLACE(%s, \'%s\', \'%s\')';
$i = 0;
foreach ($search_replace_mapping as $search => $replace)
{
$s = sprintf($template, ($i == 0 ? '\''. $telephone_number .'\'' : $s), $search, $replace);
$i++;
}
$s = 'SELECT '. $s .' AS normalized FROM Accommodation';
return $s;
}
$numbers = array(
'0049 03831 667 156',
'+39 0471 / 975 642',
'+0039 6757 - 3939 9393',
'+49 (0) 3834 50 77 73',
'+43 (i) 4m 4n idiOt',
'+44 (0) 1234 \\ 55 55'
);
print_r($numbers);
$numbers_clean = array();
foreach ($numbers as $number)
{
$numbers_clean[] = normalizeTelephoneNumber($number, $search_replace_mapping);
}
print_r($numbers_clean);
$sql = array();
foreach ($numbers as $number)
{
$sql[$number] = generateSqlReplaceStatement($number, $search_replace_mapping);
}
print_r($sql);
?>
以上是关于PHP 规范化电话号码的主要内容,如果未能解决你的问题,请参考以下文章