-1

I have string with phone number that I need to transform from one format to another.

Example:

"02030266079" => "0203 026 6079"

I tried:

$num = "02030266079";
$transformed= preg_replace("/^(/d{4})(/d{3})(/d{4})$/", "$1 $2 $3", $num);

But nothing happens!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 1
    Also, as a starting point you have to define clear rules _how_ the transformation should be done. An example is not enough here. Especially since most likely one requires knowledge about where to place those spaces. Knowledge about what part of the sequence is an area code and the like. This is not trivial. – arkascha May 27 '15 at 09:28
  • 1
    Read this http://stackoverflow.com/questions/4708248/formatting-phone-numbers-in-php –  May 27 '15 at 09:28
  • Start by explaining the pattern that defines the format - eg. InternationalDialingCode+LocalDiallingCode+Number – foxbeefly May 27 '15 at 09:28
  • Sorry. I'm new to this site and I promise to ask better questions next time. – user2546940 May 27 '15 at 09:31
  • 1
    @user2546940 no prob, next time you should come with attempts. Here `preg_replace('~(?<=^\d{4})|(?=\d{4}$)~', ' ', $str);` is the answer for this question. – Avinash Raj May 27 '15 at 09:32
  • @user2546940 You don't have to wait until next time. You can [**edit**](http://stackoverflow.com/posts/30478285/edit) your question right now – Rizier123 May 27 '15 at 09:33
  • You can use this awesome library to change the format of your number to different international of local formats https://github.com/giggsey/libphonenumber-for-php http://giggsey.com/libphonenumber/ – ThaDafinser May 27 '15 at 09:36
  • Digit is `\d` not `/d` – Toto Aug 23 '17 at 10:25

1 Answers1

2
$number = "12345678901";
$formatted_number = preg_replace("/^(\d{4})(\d{3})(\d{4})$/", "$1 $2 $3", $number);

It is php code and well tested, It works perfectly