phpregexphone-numbersanitizationleading-zero

Replace leading digits in a string if consists of optional zeros then 2 specific numbers


I get a phone number, where I would like to replace

0049
049
49

with a null.

I can do it like this:

$phone = str_replace("0049", "0", $phone);
// and so on

But for the case that a "049" is in the middle of the phone number:

00491384004924

Fail!! :/

How can I do it better?


Solution

  • does the phone got fixed length (like mobile number) ? if so , then check length of phone number and remove first symbols based on the lenght. something like this

    $phone = "00491384004924";
    if(strlen($phone) > 10) {
        $removeFirst = strlen($phone) - 10 ; 
        $phone = substr($phone, $removeFirst); // remove the first 4 symbols
        echo $phone = "0".$phone;
    }
    

    and result is

    01384004924