This question has already been answered:

Suppose there is a line with the number of the form 79167364857 . How can you bring it to the form, for example, +7 (916) 736-48-57 , but also to work not only for 916 , but for any code of regions of Russia? Maybe there are some regular solutions for PHP? Or regular season. Or is it still to "step" on the last character manually?

PS In all the above links, the answer is only for a code of 3 characters.

Reported as a duplicate by Visman , aleksandr barakin , Pavel Mayorov , Denis , fori1ton Nov 1 '16 at 6:49 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

2 answers 2

+7 is the code of the Russian Federation.

In other countries, the number of digits in the number is different. Therefore, a universal solution is difficult to achieve.

An example of a question can be done through the regular schedule.

 $p = '79167364857'; $s = preg_replace('#(\d)(\d{3})(\d{3})(\d{2})(\d{2})#', '+$1 ($2) $3-$4-$5', $p); 
  • Within one country, the number of digits in the code (city) and the number itself may differ. - andy.37
  • one
    (\d){3} or (\d{3}) ? - Qwertiy
  • @Qwertiy thanks, corrected. - Mrak

This option came up if you focus on the Russian numbers:

 $phone = '79167364857'; if(preg_match( '/^(\d)(\d*)(\d{3})(\d{2})(\d{2})$/', $phone, $matches)) { $result = '+7 ('.$matches[2].') '.$matches[3].'-'.$matches[4].'-'.$matches[5]; } //Output: $result = +7 (916) 736-48-57 

A source

Or a variation from the previous answer, also taking into account the city code:

 $p = '89167364857'; $s = preg_replace('/^(\d)(\d*)(\d{3})(\d{2})(\d{2})$/', '+7 ($2) $3-$4-$5', $p); //Output: $s = +7 (916) 736-48-57 

For 2.4 itd characters also works:

 $a = '84967364857'; $s = preg_replace('/^(\d)(\d*)(\d{3})(\d{2})(\d{2})$/', '+7 ($2) $3-$4-$5', $p); //Output: $s = +7 (4967) 736-48-57 
  • What will be wrong for any phone Podolsk, looking +7 (4967) 333-222 - andy.37
  • @ andy.37, well, instead of {3} you can then use * - BwehaaFox
  • can not. \d* just take all the numbers - andy.37 pm
  • @ andy.37, At least, if you use ^ and $ , then in this case, since there is only one non-static part, it will simply stretch. Checked on 2, and 3, and 4 characters in the code. - BwehaaFox