Reputation: 4404
I've got one javascript port of the libphonenumber package and it has the function below:
function cleanPhone(a){
a=a.replace(/[^\d\+]/g,"");
return a="+"==a.substr(0,1)?"+"+a.replace(/[^\d]/g,""):a.replace(/[^\d]/g,"")
}
I'm trying to convert this function to PHP and was wondering if this is correct:
function cleanPhone($a) {
$a = preg_replace('/[^\d\+]/g',"", $a);
return $a = "+" == substr(0,1)?"+"+ preg_replace('/[^\d]/g',"", $a) : preg_replace('/[^\d]/g',"", $a);
}
Upvotes: 0
Views: 52
Reputation: 2329
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.
I would write it more clearly:
function cleanPhone($a) {
$a = preg_replace('/[^\d\+]/', "", $a);
if(substr($a, 0, 1) == "+"){
return "+" + preg_replace('/[^\d]/', "", $a);
}else{
return preg_replace('/[^\d]/',"", $a);
}
}
Also notice you were missing the variable identifier for the substring method substr($string, $startIndex, [$length])
The minified version using a ternary operator should also work:
function cleanPhone($a) {
$a = preg_replace('/[^\d\+]/',"", $a);
return ("+" == substr($a,0,1))?"+"+ preg_replace('/[^\d]/',"", $a) : preg_replace('/[^\d]/',"", $a);
}
Upvotes: 1