CoolCodeGuy
CoolCodeGuy

Reputation: 44

How to turn a phone number into a new form (with area codes)

I am trying to find a way of turning a phone number (+4407111111111) to something like 44711111111.

Basically I am asking for something which will get delete the zero and the +. Also if the person could chose a area code.

Thanks :-)

Upvotes: 0

Views: 219

Answers (3)

maxhb
maxhb

Reputation: 8865

Use preg_replace() to transform phone number to desired output:

$phone = '+4407111111111';
$newPhone = preg_replace('/^\+([1-9]+)0(\d+)$/','$1$2',$phone);
echo $newPhone;

Explanation of regular expression:

  1. ^ = Start at beginning of string
  2. + = match a "+"
  3. ([1-9]+) = match a sequence of digits from 1 to 9 and assign them to $1
  4. 0 = match one "0"
  5. (\d+)$ = match all digits up to the end of the string and assign match to $2

Replacement is simple, just use "$1$2" as defined in above explanation.

Better than trying to split up a given phone numer is to fetch data for country code, area code and phone number as seperate values. Makes things much easier and delivers better results because phone numbers may be handled a little bit different from country to country.

Upvotes: 2

Hassan Naqvi
Hassan Naqvi

Reputation: 423

Give your users option to provide you country code, area code and phone number separately. I've seen my form that use your approach and I cant add my phone number to those forms +932134564545 (obviously, not my correct number but digits are same :) )

Upvotes: 0

Somil
Somil

Reputation: 597

If you just want to delete a 0 and + you can use preg_replace function of php. If you want to split the number into country code , area code and actual number that in that case you need to have a separator already in place.

Upvotes: 0

Related Questions