Phone number formatting PHP

With the APIs of a third part web application, I retrieve the data of the customer including email, country, phone number and so on.
Let's imagine that I have a customer that inserts in that web application a phone number incorrectly. I've created two types of check to correct the phone number:

//phone prefix totally missing
if( substr($phone_number, 0, 1) != '+' ) {
    if( substr($phone_number, 0, 2) == '00' ) {
        $phone_number = '+'.substr($phone_number, 2);
    } else {
        $phone_number = $this->params['prefix'].$phone_number;
    }
}


// double prefix prevention (since October 2019)
if (substr($phone_number, 0, 1) == '+' && substr($phone_number, 0, 3) == substr($phone_number, 3, 3)) {
    $phone_number = substr($phone_number, 3);
} else if(substr($phone_number, 0, 1) == '+' && substr($phone_number, 0, 2) == substr($phone_number, 2, 2)) {
    $phone_number = substr($phone_number, 2);
} else if(substr($phone_number, 0, 1) == '+' && substr($phone_number, 0, 4) == substr($phone_number, 4, 4)) {
    $phone_number = substr($phone_number, 4);
}


There's anyway a problem. Let's imagine that a customer inserts the following incorrect phone number: "39 3939xxxxxx", where the first "39" is the Italian prefix without the + that is missing (so, the phone number is not correct).
In this case, I'm totally lost, since if I remove the "39", then I would remove also half of the number; if I add instead a + to the "39"s, I risk to have something like "+39+39+39xxxxxx".
The main problem is that I don't know if the prefix is included in the number or not, so I'm stuck here, since I don't know what kind of control implement without leaving any margin of error.
EDIT: I've noticed that there's a Google library available to help with this issue, but it's a problem for me to integrate it in my web application at the moment.
  • 1
    Considering that the prefix is the first character couldn't you just check if it is there and if not you'll add it? – Synapsis 20 mins ago
  • Are you comfortable with RegEx ? – Cid 19 mins ago
  • @Synapsis yes I could, but what about the case of the number 39 3939xxxxxx I've described? I would add another +39, which would generate a number of 14 cyphers including the prefix, which is incorrect. – Lorenzo 16 mins ago
  • @Cid honestly, not that much.. but what is your suggestion anyway? – Lorenzo 15 mins ago
  • That's just a thought, but if you aren't comfortable with RegEx, that will be giving you some code you can't maintain – Cid 13 mins ago
0
  • Link only answers are bad. Include some code from the website cause if the code gets removed then it won't be useful anymore for people experiencing the same problem in the future – Synapsis 15 mins ago
  • I've already noticed that library, thanks anyway. Is there any other way to solve this situation without that library? It would be complex to integrate with my web application. – Lorenzo 14 mins ago

Post a Comment

0 Comments