format and trim number - php

Is there a way In PHP to just get the first two digits from any given number so for instance:
get 17 from 1700,
14 from 1457,
13 from 130
and if digits are single or double digits leave them as they are.
And at last is there a way to find out if the last two digits of four digit number are zeros so, for instance, distinguish 1700, 1600 etc.

(1) To get the first two digits in php you'll want to use the substr method, as described here:
http://php.net/manual/en/function.substr.php
(2) I'm not clear on what you mean by "leave them as they are" here:
if digits are single or double digits leave them as they are.
(3) For searching for characters in a larger string I would suggest using regular expressions as described here:
http://php.net/manual/en/reference.pcre.pattern.syntax.php
Please note, PCRE regular expressions are a very broad subject, so be sure you really need them. A famous quip about programmers and problems comes to mind.

if (substr($foo, -2) == 00) { // Check if last two digits are zero
echo "double zero!"; // Do something if they are
}
if (strlen($foo) > 2) { // Check if there are more than 2 digits
$foo = substr($foo, 0, 2); // If so only return the first 2 digits
}
echo $foo;

Related

PHP Regex Regular Expressions preg_match() only allow digits with commas

I've asked and it was answered but now, after years, it doesn't work.
I've even tried online regex validators. Not sure what is going on.
Version: PHP 7.0.30 on 64Bit OS
The string should only allow digits with commas.
No commas in the beginning or end.
Spaces between commas is ok but I'd rather not allow it.
The following isn't passing
My regex is:
$DateInvoicedIDs = "1031,453,808,387,111,342,962,706,251,442,362,858,950,738,310,288,99,665,1023,30,894,112,132,148,347,895,382,94,766,683,276,1104,658,34,348,235,786,769,2";
$reg = '/[0-9\s]+(,[0-9\s]+)*[0-9]$/';
if ( preg_match($reg, $DateInvoicedIDs) ) {
echo = $DateInvoicedIDs;
} else { echo "false"; }
I'm using preg_match and getting false.
Any idea?
Test your string and pattern # https://regex101.com/r/3TVmOv/1
When that loads, you will see that there is no match highlighted.
Then add a digit to the end of your string and Whalla! This is because (,[0-9\s]+)* is matching the final 2 and [0-9]$ cannot be satisfied because another digit is required.
If I understand your logic/requirements, I think I'd use ~^\d+(?:\s*,\s*\d+)*$~
This improves the validation because it doesn't allow a mixture of digits and spaces between commas like: 2, 3 4 56, 72 I don't think you want spaces in your comma-separated numerical values.
Pattern Demo
Code: (Demo)
$DateInvoicedIDs = "1031,453,808,387,111,342,962,706,251,442,362,858,950,738,310,288,99,665,1023,30,894,112,132,148,347,895,382,94,766,683,276,1104,658,34,348,235,786,769,2";
$reg = '/^\d+(?:\s*,\s*\d+)*$/';
if (preg_match($reg, $DateInvoicedIDs)) {
echo $DateInvoicedIDs;
} else {
echo "false";
}
It is not matching because of the last [0-9] in your regex. The * in (,[0-9\s]+)* is a greedy match which means that it is consuming all commas followed by digits in your string. There is nothing left after to match against the last [0-9].
So you probably want to reduce your regex to '/[0-9\s]+(,[0-9\s]+)*$/.
The last part of your regex [0-9]$ is what's causing it to fail:
[0-9\s]+ is matching the first number only 1031,
(,[0-9\s]+)* is covering everything until ,2 because it's a single number right after a comma which is what it's looking for
Then [0-9]$ is trying to find one more number but it can't
If the last number is a double-digit number, i.e. ,25 instead of 2, then the that second part (,[0-9\s]+)* would be satisfied because it found at least one number and [0-9]$ would match the next number which is 5 (https://regex101.com/r/0XbHsw/1)
Adding ? for that last part would solve the problem: [0-9\s]+(,[0-9\s]+)*[0-9]?$

How to match those numbers?

I have an array of numbers, for example:
10001234
10002345
Now I have a number, which should be matched against all of those numbers inside the array. The number could either be 10001234 (which would be easy to match), but it could also be 100001234 (4 zeros instead of 3) or 101234 (one zero instead of 3) for example. Any combination could be possible. The only fixed part is the 1234 at the end.
I cant get the last 4 chars, because it can also be 3 or 5 or 6 ..., like 1000123456.
Whats a good way to match that? Maybe its easy and I dont see the wood for the trees :D.
Thanks!
if always the first number is one you can use this
$Num=1000436346;
echo(int)ltrim($Num."","1");
output:
436346
$number % 10000
Will return the remainder of dividing a number by 10000. Meaning, the last four digits.
The question doesn't make the criteria for the match very clear. However, I'll give it a go.
First, my assumptions:
The number always starts with a 1 followed by an unknown number of 0s.
After that, we have a sequence of digits which could be anything (but presumably not starting with zero?), which you want to extract from the string?
Given the above, we can formulate an expression fairly easily:
$input='10002345';
if(preg_match('/10+(\d+)/',$input,$matches)) {
$output = $matches[1];
}
$output now contains the second part of the number -- ie 2345.
If you need to match more than just a leading 1, you can replace that in the expression with \d to match any digit. And add a plus sign after it to allow more than one digit here (although we're still relying on there being at least one zero between the first part of the number and the second).
$input='10002345';
if(preg_match('/\d+0+(\d+)/',$input,$matches)) {
$output = $matches[1];
}

php preg_replace frustration

Im reluctant to ask but I cant figure out php preg_replace and ignore certain bits of the sting.
$string = '2012042410000102';
$string needs to look like _0424_102
The showing numbers are variable always changing and 2012 changes ever year
what I've tried:
^\d{4}[^\d{4}]10000[^\d{3}]$
^\d{4}[^\d]{4}10000[^\d]{3}$
Any help would be appreciated. I know it's a noob question but easy points for whoever helps.
Thanks
Your first regex is looking for:
The start of the string
Four digits (the year)
Any single character that is not a digit nor { or }
The number 10000
Any single character that is not a digit nor { or }
The end of the string
Your second regex is looking for:
The start of the string
Four digits (the year)
Any four characters that are not digits
The number 10000
Any three characters that are not digits
The end of the string
The regex you're looking for is:
^\d{4}(\d{4})10000(\d{3})$
And the replacement should be:
_$1_$2
This regex looks for:
The start of the string
Four digits (the year)
Capture four digits (the month and day)
The number 10000
Capture three digits (the 102 at the end in your example)
The end of the string
Try the following:
^\d{4}|10000(?=\d{3}$)
This will match either the first four digits in a string, or the string '10000' if there are three digits after '10000' before the end of the string.
You would use it like this:
preg_replace('/^\d{4}|10000(?=\d{3}$)/', '_', $string);
http://codepad.org/itTgEGo4
Just use simple string functions:
$string = '2012042410000102';
$new = '_'.str_replace('10000', '_', substr($string, 4));
http://codepad.org/elRSlCIP
If they're always in the same character locations, regular expressions seem unnecessary. You could use substrings to get the parts you want, like
sprintf('_%s_%s', substr($string,4,4), substr($string,13))
or
'_' . substr($string,4,4) . '_' . substr($string,13)

PHP phone number parser

Building an application for UK & Ireland only but potentially it might extend to other countries. We have built an API and I'm trying to decided how A) to store phone numbers B) how to write a parser to understand all formats for entry and comparision.
e.g.
Say a user is in Ireland they add a phone number in these formats
0871231234
087 123 1234
087-1231234
+353871231234
Or any other combination of writing a number a valid way. We want to allow for this so a new number can be added to our database in a consistent way
So all the numbers above potentially would be stored as 00353871231234
The problem is I will need to do parsing for all uk as well. Are there any classes out there that can help with this process?
Use regular expressions. An info page can be found here. It should not be too hard to learn, and will be extremely useful to you.
Here is the regular expresssion for validating phone numbers in the United Kingdom:
^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$
It allows 3, 4 or 5 digit regional prefix, with 8, 7 or 6 digit phone number respectively, plus optional 3 or 4 digit extension number prefixed with a # symbol. Also allows optional brackets surrounding the regional prefix and optional spaces between appropriate groups of numbers. More can be found here.
This Stackoverflow link should help you see how regular expressions can be used with phone numbers internationally.
?php
$array = array
(
'0871231234',
'087 123 1234',
'087-1231234',
'+353871231234'
);
foreach($array as $a)
if(preg_match("/(^[0-9]{10}$)|(^[0-9]{3}\ [0-9]{3}\ [0-9]{4}$)|(^[0-9]{3}\-[0-9]{7}$)|(^\+353[0-9]{9}$)/", $a))
{
// removes +35
$a = preg_replace("/^\+[0-9]{2}/", '', $a);
// removes first number
$a = preg_replace("/^[0-9]{1}/", '', $a);
// removes spaces and -
$a = preg_replace("/(\s+)|(\-)/", '', $a);
$a = "00353".$a;
echo $a."\n";
}
?>
Try http://www.braemoor.co.uk/software/telnumbers.shtml
Design the basic functionality for the UK first add on to it later if needed. You can separate the logic for each country if needed at a later stage. I would tend on the side of cautious optimism, you want to be accepting as many numbers as possible?
Strip out spaces, opening and closing brackets and -
If number starts with a single 0 replace with 00
If number starts with a + replace with a 00
If it is numeric and has a total length of between 9 and 11 characters we are 'good'
As for storage you could store it as a string... or as an integer, with a second field that contains the Qty of prefix '0's
Use this for reference
http://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom

Validating International Phone Numbers in PHP [duplicate]

This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Closed 4 years ago.
I've been searching for hours to find a regex that does this for me, all the ones I've found either require dashes or limit something else that I don't need.
Like this one:
^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
Basically I want to allow these types of input for phone number, these are all valid:
+000 111111111
+00011111111111
0022 111111111111
0022111111111
+333-4444-5555-6666
000-7878787-0000-4587
Note that the number of digits is not limited, I only want the validation to filter out empty inputs and the alphabet. Also filter out all other characters except a maximum of 4 dashes, max. 4 spaces and an optional single plus sign.
Is this possible through preg_match or not?
Any help is appreciated, thanks!
Sure its possible. But to my opinion dangerous to use stuff that is not understood. I would do something like this
^(?!(?:\d*-){5,})(?!(?:\d* ){5,})\+?[\d- ]+$
See it here on Regexr
The last part \+?[\d- ]+ allows an optional + followed by at least one digit, dash or space
The negative lookaheads ensure that there are not more than 4 dash or spaces.
Limitations:
- The dash or space can be in one row
- it accepts also - as valid
Try it yourself on the Regexr link, you can just add examples what you want.
Strip wanted characters out (" ", "-"), count the amount then chuck an if statement if count <= 4 (for the "+" character it would be == 1). So in total it would be
if (countSpace <= 4 && countDash <= 4 && countPlus == 1) {
...
}
As for being empty, just use the standard form validation for checking if the input has been filled or not.

Categories