我有一个 libphonenumber 包的 javascript 端口,它具有以下功能:
function cleanPhone(a){
a=a.replace(/[^\d\+]/g,"");
return a="+"==a.substr(0,1)?"+"+a.replace(/[^\d]/g,""):a.replace(/[^\d]/g,"")
}
我正在尝试将此函数转换为 PHP,并且想知道这是否正确:
function cleanPhone($a) {
$a = preg_replace('/[^\d\+]/g',"", $a);
return $a = "+" == substr(0,1)?"+"+ preg_replace('/[^\d]/g',"", $a) : preg_replace('/[^\d]/g',"", $a);
}
最佳答案
g is not a valid modifier in PCRE (the regex implementation PHP uses) because it's simply not needed; preg_replace() will perform global replacements by default. You'll find the modifier in true Perl regex as well as JavaScript regex, but not in PCRE.
我会写得更清楚:
function cleanPhone($a) {
$a = preg_replace('/[^\d\+]/', "", $a);
if(substr($a, 0, 1) == "+"){
return "+" + preg_replace('/[^\d]/', "", $a);
}else{
return preg_replace('/[^\d]/',"", $a);
}
}
另请注意,您缺少 substring 方法的变量标识符 substr($string, $startIndex, [$length])
使用 ternary operator 的缩小版本也应该有效:
function cleanPhone($a) {
$a = preg_replace('/[^\d\+]/',"", $a);
return ("+" == substr($a,0,1))?"+"+ preg_replace('/[^\d]/',"", $a) : preg_replace('/[^\d]/',"", $a);
}
关于JavaScript 到 PHP 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31147369/