简体   繁体   中英

Replace first character of a String if first character is 0

I'm pulling records from a table with a phone_number field. In the table some of the phone numbers are not in correct order. The right order should have been 233 then followed by the user's phone numbers but some records starts with the user's phone number.

ie: instead of 233243000 (233xxxxxx so correct order) some phone numbers are like: 0243000 (ie not correct order)

What i want to do is if the number only starts with zero, it should be replaced with 233 so that all the numbers become in correct order.

Test the first character and if it is zero, replace it.

if (substr($pn, 0, 1) === '0') {
   $pn = '233' . substr($pn, 1);
}

You may also want to use other criteria, such as the length of the original value, etc, to ensure that your result is what you expect, and not an exceptional value. For example if the original value is 023333623236 then performing the above transformation may not be what you want.

$number = '043234';
$const = '233';
if(substr($number,0) === '0'){
echo $number  = $const.''.substr(1, strlen($number));
}
else{
echo $number;
}
$phoneNumber = '023343234';
$countryCode = '233';

if(substr($phoneNumber, 0, 4) == '0233'){
    // if the number has 233 but it started with 0
    echo $phoneNumber  = $countryCode.''.substr($phoneNumber, 4);

}elseif(substr($phoneNumber, 0, 1) == '0'){
    // if the number started with 0
echo $phoneNumber  = $countryCode.''.substr($phoneNumber, 1);
}else{
    // if the number is in correct format
echo $phoneNumber;
}

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