gpt4 book ai didi

JavaScript 到 PHP 的转换

转载 作者:行者123 更新时间:2023-12-03 09:42:21 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com