简体   繁体   English

如果第一个字符为0,则替换字符串的第一个字符

[英]Replace first character of a String if first character is 0

I'm pulling records from a table with a phone_number field. 我从带有phone_number字段的表中提取记录。 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. 正确的顺序应该是233然后是用户的电话号码,但是某些记录以用户的电话号码开头。

ie: instead of 233243000 (233xxxxxx so correct order) some phone numbers are like: 0243000 (ie not correct order) 即:代替233243000(即233xxxxxx正确的顺序),一些电话号码类似于:0243000(即不正确的顺序)

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. 我想做的是,如果数字仅以零开头,则应将其替换为233,以便所有数字都以正确的顺序排列。

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. 例如,如果原始值为023333623236,则执行上述转换可能不是您想要的。

$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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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