formatting local mobile to international in php - php

I am looking for a simple regex to convert both UK (44) and Indian (91) numbers into a valid international format using PHP. The formats required are:
447856555333 (for uk mobile numbers)
919876543456 (for indian mobile numbers)
I need a regex that will accept and format the following variations:
1) 07856555333
2) 0785 6555333
3) 0785 655 5333
4) 0785-655-5333
5) 00447856555333
6) 0044785 6555333
7) 0044785 655 5333
8) 0044785-655-5333
9) 00447856555333
10) +447856555333
11) +44785 6555333
12) +44785 655 5333
13) +44785-655-5333
14) +919876543456
15) 00919876543456
Any help would be much appreciated.
UPDATE: Based on answer below I have amended the code slightly and it works very well. It is not bullet proof but covers most of the popular formats:
public static function formatMobile($mobile) {
$locale = '44'; //need to update this
$sms_country_codes = Config::get('sms_country_codes');
//lose any non numeric characters
$numeric_p_number = preg_replace("#[^0-9]+#", "", $mobile);
//remove leading zeros
$numeric_p_number = preg_replace("#^[0]*#", "", $numeric_p_number);
//get first 2 digits
$f2digit = substr($numeric_p_number, 0,2);
if(strlen($numeric_p_number) == 12) {
if(in_array($f2digit, $sms_country_codes) ) {
//no looks ok
}
else {
return ""; //is correct length but missing country code so must be invalid!
}
}
else {
if(strlen($locale . $numeric_p_number) == 12 && !(in_array($f2digit, $sms_country_codes))) {
$numeric_p_number = $locale . $numeric_p_number;
//the number is ok after adding the country prefix
} else {
//something is missing from here
return "";
}
}
return $numeric_p_number;
}

for your particular scope think something like this might work ... not really a regex-only solution but should do the trick for your needs:
$locale = "your_locale_prefix";
$valid_codes = array("44","91");
//loose any non numeric characters
$numeric_p_number = preg_replace("#[^0-9]+#", "", $phone_number);
//remove leading zeros
$numeric_p_number = preg_replace("#^[0]*#", "", $numeric_p_number);
//get first 2 digits
$f2digit = substr($numeric_p_number, 0,2);
if(in_array($f2digit, $valid_codes) && strlen($numeric_p_number) == 12){
//code is ok
} else {
if(strlen($locale . $numeric_p_number) == 12) {
//the number is ok after adding the country prefix
} else {
//something is missing from here
}
}

Related

Universal Mobile number validation pattern in PHP

Here is My working Code, if you got a better one post below.
Took me hours to build.
Number can be between (4-15) Universal Standard.
Might contain '+' at the beginning and '-' is allowed once with allowed format like ('1+123,12+123,+1-123,+12-123).
Rest all spaces and '-' and '+' will be replaced by blank and a proper Number will be returned.
public function validateMobileNumber($mobile){
$mobile = str_replace(' ','',$mobile);//remove all the blank spaces i.e +1-123456342234
//now let's do it for mobile numbers
if(preg_match('/^([0-9,\\-,+,]){4,15}$/', $mobile)){//pratially valid number
$mobile = rtrim($mobile, "+");
$mobile = trim($mobile, "-");
//removing multiple '-'
$mobile_arr = explode('-',$mobile);//elplode a number like +1-123 456-342-234
$sub1 = $mobile_arr[0];//+1
if(strlen($sub1) != strlen($mobile)){ // condition where 12345678 valid nos is detected
$check_plus = explode('+',$sub1); //logic to detect number starts with +1-123.. or +12-123.. or 1-123.. or 12-123...
if($check_plus[0] == ''){ // occurs when we get +1...
if(strlen($sub1) == 2 || strlen($sub1) == 3){//valid digits like +1-123, +12-123
unset($mobile_arr[0]);
} else {
//invlid number
return array('status'=>'error','message'=>'Number must be in +1-123.. or +12-123.. or 1-123.. or 12-123... format');
}
} else {
if(strlen($sub1) == 1 || strlen($sub1) == 2){//valid digits like 1-123, 12-123
unset($mobile_arr[0]);
} else {
//invlid number
return array('status'=>'error','message'=>'Number must be in 1-123.. or 12-123.. or +1-123.. or +12-123... format');
}
}
$mobile = $sub1 .'-'.implode('',$mobile_arr);//+1-123 456342234
}
//removing '-' ends
//removing '+'
$mobile_arr = explode('+',$mobile);//explode a number like +1-123 456+342-234
if($mobile_arr[0]!='') {
if (strlen($mobile_arr[0]) != strlen($mobile)){ //number might be 1-123 456+342-234+
return array('status'=>'error','message'=>'Number must have "+" at the start ');
}
} else {
if($mobile_arr[2]!=''){//when we have more than one +
$sub1 = $mobile_arr[1];
unset($mobile_arr[1]);
$mobile = '+'.$sub1.implode('',$mobile_arr);//+1-123 456342234
}
}
return array('status'=>'success','data'=>$mobile);
} else {
return array('status'=>'error','message'=>'Invalid Mobile Number.');
}
//Validate Mobile number logic ends
}

check if numeric php

my problem is, i have a form which i fill blabla and after i submit i need to check if the var '$number' contains only 9 numbers. which means that if it contains at least 1 letter or has less or more than 9 length it should return false, else it should return true;
this is what i got so far:
if (!is_numeric ($number) {
//do
} else {
}
1st problem: This code should take care of the only numbers part but it doesnt, it always returns false.
2nd: do you guys know of any way to take care of the 9 digits only verification?
thanks and sorry for my bad english, not my native language :P
Your number may contain unwanted whitespaces which cause the is_numeric() test not to work properly
So do the following: $number = trim($number); to remove them.
Then indeed this snippet is good to check if your variable is a number:
if (!is_numeric ($number)) {
//do
} else {
}
And for the number digits do a if statement to see if your number is between 100000000 and 999999999
So the full code will be:
$number = trim($number);
if (!is_numeric ($number)) {
//do
} else {
if ($number >= 100000000 && $number <= 999999999) {
// Everything is ok
} else {
}
}
Didn't understood your complete question coz of you native language :p, but i think you want this:
if (is_numeric($number) {
if(strlen($number) == 9){
return true;
} else {
return false;
}
} else {
echo 'Not a number';
}
Check if it contains digits and check whether its exactly contains 9.
$number = '123456789';
if(!preg_match('/^\d{9}$/', $number)) {
echo 'not ok';
} else {
echo 'ok';
}

PHP Function that Counts String Length and Charges Price Based on # of Characters

I've got an OpenCart VQMod that currently counts string length and charges by character. It works perfectly, but I need it to charge with the following rules:
30-45 characters: $8.50
46+ characters: $12.00
Edit:
As of now, this mod multiplies the string length with a set price per character, but I need it to only charge a flat $8.50 for 30-45 characters, or $12 for 46+ characters. Can anyone help me modify the following PHP? I'm pasting the entire file here. Thanks so much for your responses so far. I really appreciate the help of the community.
Edit 2: Removed unnecessary code, only showing string length potion.
//Q: Option Price By Character
$optprice = '';
$optprefix = '';
if ($option_query->row['type'] == 'text' || $option_query->row['type'] == 'textarea') {
if (strlen($option_value)) {
$optprice = (strlen($option_value) * $option_query->row['price_per_char']);
$optprefix = '+';
$option_price += $optprice;
if ($option_query->row['type'] == 'text' || $option_query->row['type'] == 'textarea') {
if (strlen($option_value)) {
// LumberJack's new code
$string_length = strlen($option_value);
if($string_length >= 30 && $string_length <= 45)
{ $optprice = 8.5; }
else if($string_length >= 46)
{ $optprice = 12.00; }
else {
// end my new code
$optprice = (strlen($option_value) * $option_query->row['price_per_char']);
} // I moved this up two lines
$optprefix = '+';
$option_price += $optprice;
}
}
First find out which one is the greatest number. in this case, its 45.
$price = 8.50;
for(i=1;i<45;i--){
echo i - $price.'<br/>';
if(i < $price){
break;
}
}

How do I retrieve house number in magento street value via soap?

I have magento, and I'm posting a request via the soap v2 api to get the address of an order.
With that I get the following object which contains the street name + housenumber(God knows why these fields are not seperate...)
$shipping_address->street = "4th avenue 108";
Now what I want is to have the housenumber 108.
How do I get this house number without getting the 4?
(if someone has a more reliable function/piece of code than the one I post below, please feel free to post it.)
What you basically have to do is check for the first number occurence with a space in front of it.
This way you minimse the risk of fetching the wrong number:
// Code by Michael Dibbets
// shared under creative commons Attribution 3.0 Unported (CC BY 3.0 http://creativecommons.org/licenses/by/3.0/ )
$value = "4th street26";
$spl = str_split($value);
$pos = 0;
$location = 0;
// simple loop to find the first character with space + integer
foreach($spl as $char)
{
if(is_numeric($char) && $spl[$pos-1]==' ')
{
$location = $pos;
break;
}
$pos++;
}
// If we didn't encounter the space + integer combination
if(!$location)
{
// is the last character an integer? Assume that the last numbers are house numbers
if(is_numeric($spl[count($spl)-1]))
{
for($c=count($spl)-1;$c>0;$c--)
{
if(is_numeric($spl[$c]))
{
continue;
}
else
{
$location = $c+1;
break;
}
}
}
}
if($location)
{
$street = substr($value,0,$location);
$number = substr($value,$location);
}
else
{
$street = $value;
$number = null;
}
// echoing the results. The number should appear after the dash.
echo $street . ' - ' . $number;

If statement to check the number of characters in a textbox

when the user adds a contact, it checks to see if the "character" count is 8, then it check the database to see if the username and the NewContact already exist, and if it "false", it inserts the new contact.
the bit that doesn't work is limiting the number of characters to 8
if (intval($s_id) == 8)
{
$db = mysql_connect("at-web2.xxx", "user_xxx", "xxxx");
mysql_select_db("db_xxx",$db);
$result = mysql_query("SELECT * FROM contacts WHERE u_id='$username' and c_id='$s_id'",$db);
$myrow = mysql_fetch_row($result);
if(!$myrow)
{
mysql_query("INSERT INTO contacts(u_id, c_id) VALUES ('$username','$s_id')",$db);
header("Contact Added");
}
else
{
header("Contact Already Exist");
}
}
else
{
header("Incomplete Contact");
}
You need strlen function.
if(strlen($s_id) == 8)
you have to use strlen to get number of characters
if (intval($s_id) == 8)
should be
if (strlen($s_id) == 8)
Try to use strlen with trim function to get accurate length of string.
if(strlen(trim($s_id)) == 8)
Use strlen (stringlength) predefined php function for getting the exact length of the string .
if(strlen($string) == 8)
{
//Statements
}
else
{
//statements
}

Categories