简体   繁体   中英

Format number different depending on mobile or business phone

Currently in my php application I have the following code that formats the unformatted 10 digit australian phone number to XX XXXX XXXX . What I would like to do is if the phone number in the database starts with 04 then it will format it as 4,3,3 like XXXX XXX XXX otherwise will maintain the 2,4,4 formatting. All phone numbers are stored in the database as XXXXXXXXXX .

Here is my code so hopefully someone can shed some light. I know there needs to be an if statement, but unsure how to check the first 2 digits of the number for the 04 .

<?php

    $num = $record['busphone'];
    $phoneformated = substr($num,0,2)." ".substr($num,4,4)." ".substr($num,6);

    echo "Ph: " . $phoneformated;

?>

You're on the right track. Here's an if statement

$prefix = substr($num,0,2);
if($prefix == '04') {
    $phoneformated = $prefix . " ".substr($num,2,4)." ".substr($num,-6);
} else {
    $phoneformated = substr($num,0,4)." ".substr($num,2,3)." ".substr($num,-3);
}

Compare the substring in an if statement:

if (substr($num, 0, 2) == '04') {
    $phoneformatted = substr($num, 0, 4) . " " . substr($num, 4, 3) . " " . substr($num, 7);
} else {
    $phoneformatted = substr($num, 0, 2) . " " . substr($num, 2, 4) . " " . substr($num, 6);
}

Notice that you had a typo in formatting the residential numbers, substr($num, 4, 4) should be substr($num, 2, 4) .

Match First 04 with regex

$num = $record['busphone'];
// check first 04
if( preg_match('/^04/', $num) ) {
   // Your format
   // xxxx xxx xxx
}
else {
    // xxxxxxxxxx
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM