Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim country code from phone number in php

Tags:

regex

php

I will get a country code as $countryCode and a phone number as $phone_no. The phone number will have country code at the start so I have to remove country code from the $phone_no and get plain phone number without any code attached.

For example if country is Indonesia I will be getting:

$country_code = '62';
$phone_no = '+62509758151';
// need to  get 509758151

Currently I am trying with regex and trim function

$result = ltrim( preg_replace("/[^0-9]+/", "",$phone_no) , $country_code);
// $result is 509758151

which works in this case but fails when phone number is starting with digits mentioned in the country code for ex. $phone_no = '+62609758151';

$result = ltrim( preg_replace("/[^0-9]+/", "",$phone_no) , $country_code);
// $result is 09758151 which is incorrect

Not to mention it will also fail for trivial cases like +62629758151

Please suggest something.I am aware of string based solutions like substr(), etc. but I am looking for some regex-based solution

like image 482
Vinay Avatar asked Dec 27 '17 08:12

Vinay


People also ask

How to remove country code from phone number in php?

preg_replace('/\D/', '', ($phone));

How do I remove my phone number from country code Iphone?

Your phone says dial assist because it is actively helping you to place an international call by including a country code or local prefix. You can turn it off by going to Settings > Phone > and toggling off the Dial Assist option.


1 Answers

Change start of string with sign + and country code

$result = preg_replace("/^\+?{$country_code}/", '',$phone_no);

demo

like image 59
splash58 Avatar answered Oct 16 '22 08:10

splash58