RegEx for Phone Number Numbers with Letters - php

I need to format a phone number as one long string of numbers (US Phone Number format)
// I know there are tons more
$phones = array(
'1(800) 555-1212',
'1.800.555.1212',
'800.555.1212',
'1 800 555 1212',
'1.800 CALL NOW' // 1 800 225-5669
);
foreach($phones as $phone) {
echo "new format: ".(preg_replace("/[^0-9]/", "", $phone)."<br />\n";
}
Now this should return something like this:
8005551212 (with or without the 1)
but how do I map/convert the number with CALL NOW to:
18002255669

To save some typing...
$phoneNumber = strtr($phoneLetters, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "22233344455566677778889999");

You could use strtr().
$number = strtr($number, array('A'=> '2', 'B' => '2', ... 'Z' => '9'));
Or actually, I think:
$number = strtr($number, "AB...Z", "22...9");

For the first step, you need to do a different regex replace (your version would now lose all the letters):
$result = preg_replace('/[^A-Z0-9]+/i', '', $phone);
Then, you need to take the string and replace each letter with its corresponding digit (see konforce's answer). That's not really a job for a regex.

Related

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
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.
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;

PHP - Trim text from string with a blank space from from an array

I have the following PHP code that is suppose to remove the 'excess' text when a user enters it in a field. I have the following code as follows:
$mobileNumber = '00 356 99048123';
$excessMobileNumbers = array(//remove excess items in mobile number such as dialing codes and empty spaces
// ' ' => '',
'00356' => '',
'+356' => '',
'356' => '',
'00' => '',
);
The output is 99048123
The above code works well as it the number 99048123 doesn't contain 356 or 00.
But when I use this number 00 356 99008123, the number 99008123 contains 00. I want it only to remove the 00 in the 00 i.e. starting from the left hand side and leaving without removing the 00 in the 99008123.
How do I go about it? I use the array as a 'filtering' system.
Thanks
Clarification
It is not only for 00 even for 356, if the number is 99048123 it works fine. If this number 99035612 since it has 356 withing it it does not work.
SOLUTION
I discovered this solution which seems to work for my problem.
$mobileNumber = '00 356 99048000';
$mobileNumber = str_replace(' ','',$mobileNumber); // UPDATE
$excessMobileNumbers = substr($mobileNumber, 0, -8);
$mobileNumber = str_replace($excessMobileNumbers,'',$mobileNumber);
echo $mobileNumber;
Thank you all for your contribution.
You could use regex to strip out all non-numeric characters:
preg_replace("/[^0-9]/", "", $mobileNumber);
and then use substr to grab the part that you want:
$my_number = substr($mobileNumber, -8);
This way if a number is passed in like:
$mobileNumber = '00 356 99-048-123';
or any other non-numeric characters are inside the part you actually want, after stripping out those characters you always know the last 8 characters are the numeric digits you are after.
As some suggested, try this:
$mobileNumber = '00 356 99048123';
$mobileNumberParts = explode(" ", $mobileNumber);
echo end($mobileNumberParts);
output: 99048123
As #ende-neu suggests simply explode out the string on a space and just take the last element in the array.
For the example you give this would look like:
$mobileNumber = '00 356 99048123';
$mobile_array = explode(' ',$mobile_number);
$my_number = end($mobile_array); //will give you 99048123
echo $my_number;
Although to be honest you're probably better off with a regular expression type approach or use a solid library such as libphonenumber for PHP
Use preg_replace to remove all of your listed "prefixes" (only when at the beginning (^))
$number = preg_replace('/^(00|00365|\+365|365)/', '', $mobileNumber);
That is much safer than just splitting at white space because some people might add more white space in between the last part to improve readability.
I discovered this solution and it seems to work for my case
$mobileNumber = '00 356 99048000';
$mobileNumber = preg_replace("/[^0-9]/", '', $mobileNumber);
$excessMobileCharactors = substr($mobileNumber, 0, -8);
$mobileNumber = str_replace($excessMobileCharactors,'',$mobileNumber);
echo $mobileNumber;
Thank you all for your kind help.

Extract first integer in a string with PHP

Consider the following strings:
$strings = array(
"8.-10. stage",
"8. stage"
);
I would like to extract the first integer of each string, so it would return
8
8
I tried to filter out numbers with preg_replace but it returns all integers and I only want the first.
foreach($strings as $string)
{
echo preg_replace("/[^0-9]/", '',$string);
}
Any suggestions?
A convenient (although not record-breaking in performance) solution using regular expressions would be:
$string = "3rd time's a charm";
$filteredNumbers = array_filter(preg_split("/\D+/", $string));
$firstOccurence = reset($filteredNumbers);
echo $firstOccurence; // 3
Assuming that there is at least one number in the input, this is going to print the first one.
Non-digit characters will be completely ignored apart from the fact that they are considered to delimit numbers, which means that the first number can occur at any place inside the input (not necessarily at the beginning).
If you want to only consider a number that occurs at the beginning of the string, regex is not necessary:
echo substr($string, 0, strspn($string, "0123456789"));
preg_match('/\d+/',$id,$matches);
$id=$matches[0];
If the integer is always at the start of the string:
(int) $string;
If not, then strpbrk is useful for extracting the first non-negative number:
(int) strpbrk($string, "0123456789");
Alternatives
These one-liners are based on preg_split, preg_replace and preg_match:
preg_split("/\D+/", " $string")[1];
(int) preg_replace("/^\D+/", "", $string);
preg_match('/\d+/', "$string 0", $m)[0];
Two of these append extra character(s) to the string so empty strings or strings without numbers do not cause problems.
Note that these alternative solutions are for extracting non-negative integers only.
Try this:
$strings = array(
"8.-10. stage",
"8. stage"
);
$res = array();
foreach($strings as $key=>$string){
preg_match('/^(?P<number>\d)/',$string,$match);
$res[$key] = $match['number'];
}
echo "<pre>";
print_r($res);
foreach($strings as $string){
if(preg_match("/^(\d+?)/",$string,$res)) {
echo $res[1].PHP_EOL;
}
}
if you have Notice in PHP 7 +
Notice: Only variables should be passed by reference in YOUR_DIRECTORY_FILE.php on line LINE_NUMBER
By using this code
echo reset(array_filter(preg_split("/\D+/", $string)));
Change code to
$var = array_filter(preg_split("/\D+/", $string));
return reset($var);
And enjoy! Best Regards Ovasapov
How to filter out all characters except for the first occurring whole integer:
It is possible that the target integer is not at the start of the string (even if the OP's question only provides samples that start with an integer -- other researchers are likely to require more utility ...like the pages that I closed today using this page). It is also possible that the input contains no integers, or no leading / no trailing non-numeric characters.
The following is a regex expression has two checks:
It targets all non-numeric characters from the start of the string -- it stops immediately before the first encountered digit, if there is one at all.
It matches/consumes the first encountered whole integer, then immediatelly forgets/releases it (using \K) before matching/consuming ANY encountered characters in the remainder of the string.
My snippet will make 0, 1, or 2 replacements depending on the quality of the string.
Code: (Demo)
$strings = [
'stage', // expect empty string
'8.-10. stage', // expect 8
'8. stage', // expect 8
'8.-10. stage 1st', // expect 8
'Test 8. stage 2020', // expect 8
'Test 8.-10. stage - 2020 test', // expect 8
'A1B2C3D4D5E6F7G8', // expect 1
'1000', // expect 1000
'Test 2020', // expect 2020
];
var_export(
preg_replace('/^\D+|\d+\K.*/', '', $strings)
);
Or: (Demo)
preg_replace('/^\D*(\d+).*/', '$1', $strings)
Output:
array (
0 => '',
1 => '8',
2 => '8',
3 => '8',
4 => '8',
5 => '8',
6 => '1',
7 => '1000',
8 => '2020',
)

Extract numbers from phone number input field (PHP)

I've got a phone number input field, which allows a user to add a phone number in whatever format they want (555-555-5555, (555) 555 - 5555, etc).
Since it a phone number field only, I can ignore everything but the numbers in the field.
I'm currently using the following code. It extracts all the numbers, but the issue is that they are not in order - it's in a jumbled order.
How do I extract the numbers in the order that they appear in the original string?
preg_match_all('/\d+/', $Phone, $matches);
$Phone = implode('', $matches[0]);
Edit: They are actually not in a jumbled order from this function - I was inserting the numbers into a int(10) database field, which caused the jumbling. But, the answers below are still a more efficient way of accomplishing my goal.
Use preg_replace to remove any non-digits:
$numbers = preg_replace('/[^\d]/','',$Phone);
Note: '[^\d]' can be replaced with '\D' (safe in non-unicode mode).
$Phone = preg_replace('/[^\d]/', '', $Phone);
Why not just replace everything in the string that is not a digit?
$number = preg_replace("/[^0-9]/", '', $Phone);
Try it
if (!preg_match("/^[0-9\-]*$/",$Phone)) {
echo "Only Numeric and strip (-)";
}
Example:
Good: 0877-9320-9356
Failed: 0877 9320 9356 or 087793209356

PHP and Money, converting money to cents

So I have done a fair bit of research on how to store "money" in a database and I think the system I want to use is
Converting Money into CENTS and then storing the CENTS in a MySQL DB with a field type of DECIMAL (19,4).
My question is, IF I have an input field from the user... how do I deal with multiple input types.
IE:
$input = "1,346.54"
$input = "10,985.23"
$input = "110,400.50"
$input = "1033.44"
etc etc...
What would be the best method for converting this to CENTS? As we have to deal with 'strings' and convert them to INT, and divide by 100... Everything that I try throws issues because of the "comma" separation with the numbers.
Any thoughts or direction would be greatly appreciated.
function getMoneyAsCents($value)
{
// strip out commas
$value = preg_replace("/\,/i","",$value);
// strip out all but numbers, dash, and dot
$value = preg_replace("/([^0-9\.\-])/i","",$value);
// make sure we are dealing with a proper number now, no +.4393 or 3...304 or 76.5895,94
if (!is_numeric($value))
{
return 0.00;
}
// convert to a float explicitly
$value = (float)$value;
return round($value,2)*100;
}
Looks like there is a NumberFormatter class which provides a parseCurrency method. Have a look at http://www.php.net/manual/en/numberformatter.parsecurrency.php
The example provided is
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
You can remove the commas like this:
$input = str_replace( ',', '', $input);
At this point, you can convert to cents by converting to a float and multiplying by 100. However, this is probably unnecessary. You would potential encounter precision issues when performing math operations, but simply storing the values in the database can be done in the original form without alteration of the value (assuming your DB tables are properly structured):
$input = (float)str_replace( ',', '', $input);
function convert_to_cents($v)
{
$v = str_replace(',','',$v);
$p = explode('.',$v);
if(strlen($p[1])<2){ $p[1] = $p[1]*10;}
return ($p[0]*100)+$p[1];
}
This converts most of the decimal currencies to their subunits.
$1,234,567.89 = 123456789
£ 1,234,567.89 = 123456789
€1.234.567,89 = 123456789
12,34 EUR = 1234
12,34 € = 1234
12,30 € = 1230
1,2 = 102
function convertDecimalCurrencyToSubUnit($str)
{
if( preg_match('/^(.+)[^\d](\d|\d\d)[^\d]*$/', $str, $m) )
return intval(preg_replace('/[^\d]/', '', $m[1]) . ( (strlen($m[2])>1) ? $m[2] : ('0' . $m[2]) ));
return 0;
}
Probably just remove the ',' and the '.' from the string, the result is the amount in cents.
You will probably need to parse the string from the back using strrpos ... If you find a comma 2 spots from the end, then its prob safe to assume its foreign currency and those are the CENTS... Once you determine that, use a regex to strip the remaining commas (after you convert the "CENTS" comma to a decimal of course) ... Now you have a normal DEC number to play with.
Use this to find the last comma in your string ... strrpos
Use this to replace the commas preg_replace
Here is a helpful regex website .. regexlib
//Finding the last comma
$yourCommaPos = strrpos($myString, ',');
if ($yourCommaPos == strlen($myString) - 2) {
//Comma is foreign currency decimal
// Replace with '.'
} else {
//Not foreign Currency so...
//Strip Commas
preg_replace(',', '', $myString);
}

Categories