There is a phone number that hangs on the site. It is set through the control panel. How to display a phone number with spaces? For example, replace +7 (999) 999-99-99 with +7 (999) 999-99-99 . Are there any solutions in js or php?

  • In the control panel, you can not set it with spaces immediately? - teran

3 answers 3

PHP solution with str_replace :

$output=str_replace( array('(',')'), array(' (',') '), $input ); 

    You can write a formatting function:

     function format($src, $format = '+d (ddd) ddd-dd-dd') { $digits = preg_replace('/\D/', '', $src); // Оставляем только цифры $res = ''; for($i = 0; $i < strlen($format); $i++) { $letter = $format[$i]; if (!$digits) { // Не хватило цифр $res .= $letter; continue; } switch ($letter) { case 'd': // Цифра $res .= $digits[0]; $digits = substr($digits, 1); break; default: $res .= $letter; } } return $res; } $data = [ '+7(999)999-99-99', '79998887766', '799988877', // недостаточно цифр для формата ]; foreach ($data as $phoneSrc) { echo format($phoneSrc)."\n"; } echo format('+7 (999) 888-77-66', '+d (ddd) dd-dd-ddd'); // Другой формат 

    Conclusion:

     +7 (999) 999-99-99 +7 (999) 888-77-66 +7 (999) 888-77-dd +7 (999) 88-87-766 

    Demo

      js

       '+7(999)999-99-99'.replace(/^([+]\d{1})([(]\d{3}[)])(\d{3})([-]\d{2})([-]\d{2})$/, '$1 $2 $3$4$5') 
      • Try to write more detailed answers. Add a description why this regular expression solves the problem - Grundy