0

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);
}
asked Jun 30, 2015 at 19:58
3
  • 7
    Have you tested it? Commented Jun 30, 2015 at 19:58
  • I did Sam, and got a busy signal - @JayBlanchard Commented Jun 30, 2015 at 20:00
  • yes, I have and got this first: Unknown modifier 'g' Commented Jun 30, 2015 at 20:10

1 Answer 1

1

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);
}
answered Jun 30, 2015 at 20:08
Sign up to request clarification or add additional context in comments.

2 Comments

Unknown modifier 'g'
Check now, you didn't need the g modifier

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.