skip to Main Content

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?

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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"
    /
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search