Saurabh Gujarani
Saurabh Gujarani

Reputation: 511

Converting phone Numbers into US type phone Number also for extension numbers using regExp

I tried to convert phone numbers into us type phone numbers in PHP

Which is working fine by using another method but I want to work with regExp beginner in RegExp so confused with some code I tried giving php code for better understanding

example 1 (800) 205 – 1111 -> +1-800-205-1111

+341932831111 -> +34-193-283-1111

01932831111 -> +0-193-283-1111

+12 21 2501 1111 -> +12-212-501-1111

21111 -> +2-1111

// Strip all non-numeric characters $phone = preg_replace("/[^0-9]/", "", $phone); //Calculating the length of the phone number $phoneNumberLength = strlen($phone);

// Using switch condition by phone number length switch( $phoneNumberLength ) { case $phoneNumberLength <= 7: $phone = prepare_phone_number(substr($phone, 0, 1), substr($phone, 1, 4), NULL, NULL); break; case 10: // If we have 10 digits and 1 not the first, add 1 $phone = '1' . $phone; $phone = prepare_phone_number(substr($phone, 0, 1), substr($phone, 1, 3), substr($phone, 4, 3), substr($phone, 7, 4)); break; case 11: $phone = prepare_phone_number(substr($phone, 0, 1), substr($phone, 1, 3), substr($phone, 4, 3), substr($phone, 7, 4)); break; default: $phone = prepare_phone_number(substr($phone, 0, 2 ), substr($phone, 2, 3 ), substr($phone, 5,3), substr($phone, 8,4)); } return $phone; } // Created new function to concat phone number in proper US format function prepare_phone_number($param1, $param2, $param3, $param4) { return implode( '-', array_filter( [ '+' . $param1, $param2, $param3, $param4 ] ) ); }

Upvotes: 0

Views: 80

Answers (1)

Azhy
Azhy

Reputation: 706

I have an answer to your question, also be sure there are alot of ways to do anything using regular expressions, so i don't say my answer is best, but i think it can do what do you want:-

  • Firstly reverse the phone number string which you deleted all non-numeric characters.
  • After that find captured parts of the number using below regex pattern.
  • And finally join the captured numbers however you want.

The string reversing function

strrev(str)

The regular expression pattern

/(1{4})(\d{3})?(\d{3})?(\d{1,3})/

The Code to do what i described:-

$phone = '01932831111'

/*reverse phone number*/
$phone = strrev($phone);

/*replace with (-) and (+) which do you want*/
$reg_result = preg_replace('/(1{4})(\\d{3})?(\\d{3})?(\\d{1,3})/', '$1-$2-$3-$4+', $phone);

/*if there was two captured boxes*/
$res_2 = str_replace('--', '-', $reg_result);

/*if there was three captured boxes*/
$res_1 = str_replace('---', '-', $reg_result);

/*finally reverse the string to get the result*/
$result = strrev($res_1);

echo $result;

The Result

+0-193-283-1111

Upvotes: 1

Related Questions