Elitmiar
Elitmiar

Reputation: 36839

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 would work the best, should I use regular expressions or normal string functions to perform the re-formatting? And how?

Upvotes: 1

Views: 122

Answers (3)

Mikhail
Mikhail

Reputation: 9007

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');
?>

Upvotes: 2

krtek
krtek

Reputation: 26597

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);

Upvotes: 2

M&#39;vy
M&#39;vy

Reputation: 5774

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.

Upvotes: 1

Related Questions