Search code examples
phpphone-number

Formatting Phone Numbers with country code in PHP


I am working on website that the customer submit his phone number and need to be able to convert the customer's phone number from 0553322111 to 966553322111 so I can use it to compare with the records in a MySQL database.

How would I go about this with PHP?


When the user submit his phone number in the HTML Page

He will submitted as 0553322111.

PHP

<?php
// store the submitted num.
$temp = $_POST['number']; >> 0553322111.
?> 

I want to use $temp value that stores the number and modify it to 966553322111 so I can query the records with the new value.


Solution

  • Use preg_replace:

    $phone_number = preg_replace('/^0/','966',$phone_number);
    

    /^0/ = 0 at the start of the string

    So it basically says, replace 0 at the start of the string with 966

    let me know if this works.