Jelbert
Jelbert

Reputation: 57

How to delete the first digit number in PHP

I have a data of phone number starts with +63 and 09

for example the user insert 09123456789 then save. The user shouldn't success if he enters +639123456789 because it was same number at all.

I tried using substr_replace

$data3 = substr_replace("+63", "0",0, 3);

is there other option? i think the substr_replace will have error in the future.

thanks

Upvotes: 1

Views: 1235

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

If the +63 must be at the start, you may use a preg_replace like

$s = preg_replace('~^\+63~', '0', $s);

Here,

  • ^ - start of a string position
  • \+ - a literal +
  • 63 - a 63 substring.

See the regex demo and a PHP demo.

Please also consider Tpojka's suggestion to use a combination of intl-tel-input on front-end and libphonenumber-for-php on back-end if you need to sanitize and validate international phone numbers.

Upvotes: 3

Sethu
Sethu

Reputation: 1379

In this case you can have a condition to check and have str_replace

if there is a + on your request then make remove the first 3 letters including +

if (substr($phone, 0, 1) == '+') {
    $phone = str_replace(substr($phone, 0, 3), '0', $phone);
}

$phone_number = $phone;

Upvotes: 1

Related Questions