Formatting phone number

Submitted by Jérémy on

How to transform 0123456789 to 01-23-45-67-89 ?

chunk_split

function format_tel($tel) {
    $c = chunk_split($tel, 2, '-');
    return rtrim($c, '-');
}

concat

function format_tel($tel) {
    return $tel[0].$tel[1].'-'.$tel[2].$tel[3].'-'.$tel[4].$tel[5].'-'.$tel[6].$tel[7].'-'.$tel[8].$tel[9];
}

preg_replace

function format_tel($tel) {
    $pattern = '/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
    $replacement = '${1}-${2}-${3}-${4}-${5}';
    return preg_replace($pattern, $replacement, $tel);
}

substr

function format_tel($tel) {
    return sprintf(
        '%s-%s-%s-%s-%s',
        substr($tel, 0, 2),
        substr($tel, 2, 2),
        substr($tel, 4, 2),
        substr($tel, 6, 2),
        substr($tel, 8, 2)
    );
}

Results

Function chunk_split concat preg_replace substr
Average in seconds for 1000000 calls 1.717 2.533 2.48 2.395