I've been trying to validate phone numbers to the format 5555555555 . I've successfully been able to strip the phone number of all special characters, but if a phone number is entered with +15555555555, the number still contains '1' at the beginning of the number. Is there anyway to remove both the +1 and special characters?
My current regex is preg_replace('/^1|\\D/', "", +15555555555);
.
Any help would be appreciated!
You don't need a regular expression for this.
str_replace('+1', '', $string)
will do it. However to explain why your regex currently fails, your string doesn't start with 1
, it starts with +1
so ^1
is not a match.
Demo of current usage: https://regex101.com/r/kwwp1r/1/
Demo of a possible regex solution: https://regex101.com/r/kwwp1r/2/
^\+1
Just replace the +1 from it
$phone_num = "+15555555555";
$phone_num = preg_replace('/\+1/','',$phone_num);
echo $phone_num;
or you could use str_replace('+1','',$phone_num), either or. I always use preg_replace out of habit.
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.