Home > Software engineering >  Replace leading digits in a string if consists of optional zeros then 2 specific numbers
Replace leading digits in a string if consists of optional zeros then 2 specific numbers

Time:10-17

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?

CodePudding user response:

Use preg_replace() with a start-of-string anchor

$phone = preg_replace('/^0{0,2}49/', '0', $phone);

Demo ~ https://3v4l.org/YRkeB

/
 ^      - start of line anchor
 0{0,2} - literal "0" repeated 0 to 2 times
 49     - literal "49"
/

CodePudding user response:

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
  • Related