Reputation: 3875
I have a telephone number and its type is varchar(32). It could be 03004748495,3004748495, 0300-4748495, 300-4748495,+92-300-4748495 or 923004748495. I want it to be converted in this format 923004748495 as an integer if it is not in this format. How will I achieve that? Any ideas?
Upvotes: 1
Views: 487
Reputation: 1507
Use preg_replace
to remove unwanted signs (http://php.net/manual/en/function.preg-replace.php).
<?php
$number = '+92-300-4748495';
$number = preg_replace('/[^0-9]/', '', $number);
echo $number;
If you want to remove the leading zero too, you could use rtrim
(http://php.net/manual/en/function.ltrim.php)
<?php
$number = '0300-4748495';
$number = preg_replace('/[^0-9]/', '', $number);
$number = ltrim($number, '0');
echo $number;
Additional request "If 92 is not added at the start, Add 92 also."
<?php
$number = '123456';
if (substr($number, 0, 2) != '92') {
$number = '92' . $number;
}
echo $number;
Upvotes: 1
Reputation: 718
I suggest using liphonenumber-for-php
Example code from the github page:
$swissNumberStr = "044 668 18 00";
// First call the class
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
try {
// turn it into a object using a given geo code
$swissNumberProto = $phoneUtil->parse($swissNumberStr, "CH");
// validate the phonenumber
$isValid = $phoneUtil->isValidNumber($swissNumberProto);
if($isValid){
// Produces "+41446681800"
echo $result_number = $phoneUtil->format($swissNumberProto, \libphonenumber\PhoneNumberFormat::E164);
// Produces "044 668 18 00"
echo $result_number = $phoneUtil->format($swissNumberProto, \libphonenumber\PhoneNumberFormat::NATIONAL);
// Produces "+41 44 668 18 00"
echo $result_number = $phoneUtil->format($swissNumberProto, \libphonenumber\PhoneNumberFormat::INTERNATIONAL);
}
} catch (\libphonenumber\NumberParseException $e) {
var_dump($e);
}
Upvotes: 3