Changing format of a string


I want to convert a string 40728307200 into this format:


if its not already not in this format, however, if its in that format, i want it to stay same.

However, this string is not going to be fixed, it will be dynamic.

Please suggest me a solution for this.


a string, or a number string?

Number string is easy.
(Hint: You want to use the two optional parameters, and divide by 100 first)

If you’re taking any form of input, you’ll be in a bit of trouble… though you can preg_replace anything that isnt a digit with null and end up with a number string that can then be sent through the above.

Regex or a input field mask should do?

If your taking the value from a form field, you can simply use javascript to enforce a mask.

If your taking a string regardless of it’s source, then regex is probably best.



and replacing with:


You get



echo preg_replace('/([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{2})/', '$1.$2.$3-$4', '40728307200');