简体   繁体   中英

Trim the first digit of a Phone number to be in International format

Am working on a web application whereby am capturing phone number from the user, but on the backend (build in Laravel PHP) I want to trim the first digit from the phone number and replace it with 254 .

For instance,, am capturing this phone number 07******23**
I need to replace the first zero with 254 so that it can be 2547******23**

You don't even need to invoke regex here, substr() should work just fine:

$input = "07123456789";
$output = "254" . substr($input, 1);

If you only want to do this replacement on numbers beginning with zero, then it might make more sense to use preg_replace :

$output = preg_replace("/^0/", "254", $input);

Use ltrim to remove the zero.
It will remove the zero if it's there, and leave the string intact if not.

echo "254" . ltrim($number, "0");

See example with and without the leading zero:
https://3v4l.org/Z03st

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