开发者

Formating a specific input number to another format

I need to format the following number 0825632332 to this format +27 (0)82 563 2332.

Which combination of functions w开发者_StackOverflow社区ould work the best, should I use regular expressions or normal string functions to perform the re-formatting? And how?


I think using a regexp is the best way, maybe something like this :

$text = preg_replace('/([0-9])([0-9]{2})([0-9]{3})([0-9]{4})/', '+27 ($1) $2 $3 $4', $num);

Be aware that $num must be a string since your number starts with 0.

You can also use character class :

$text = preg_replace('/(\d)(\d{2})(\d{3})(\d{4})/', '+27 ($1) $2 $3 $4', $num);


Since you asked - non regex solution:

<?php
function phnum($s, $format = '+27 (.).. ... ....') {
        $si = 0;
        for ($i = 0; $i < strlen($format); $i++)
                if ($format[$i] == '.')
                        $output[] = $s[$si++];
                else
                        $output[] = $format[$i];
        return join('',$output);
}

echo phnum('0825632332');
?>


Regex will work nicely, replace

(\d)(\d{2})(\d{3})(\d{4})

by

+27 (\1)\2 \3 \4

You can also perform string submatching if you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜