Changing format of a string

Hi,

I want to convert a string 40728307200 into this format:

407.283.072-00

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.

Thanks,
Kul.

a string, or a number string?

Number string is easy.
[FPHP]number_format[/FPHP]
(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.

Using

([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{2})

and replacing with:

$1.$2.$3-$4

You get

407.283.072-00

Script:

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