PHP - Check for leading 0's in 2 comma-delimited integers - php

I have a user-input string with 2 comma-delimited integers.
Example (OK):
3,5
I want to reject any user input that contains leading 0's for either number.
Examples (Bad):
03,5
00005,3
05,003
Now what I could do is separate the two numbers into 2 separate string's and use ltrim on each one, then see if they have changed from before ltrim was executed:
$string = "03,5";
$string_arr = explode(",",$string);
$string_orig1 = $string_arr[0];
$string_orig2 = $string_arr[1];
$string_mod1 = ltrim($string_orig1, '0');
$string_mod2 = ltrim($string_orig2, '0');
if (($string_mod1 !== $string_orig1) || ($string_mod2 !== $string_orig2)){
// One of them had leading zeros!
}
..but this seems unnecessarily verbose. Is there a cleaner way to do this? Perhaps with preg_match?

You could shorten the code and check if the first character of each part is a zero:
$string = "03,5";
$string_arr = explode(",",$string);
if ($string_arr[0][0] === "0" || $string_arr[1][0] === "0") {
echo "not valid";
} else {
echo "valid";
}

Here is one approach using preg_match. We can try matching for the pattern:
\b0\d+
The \b would match either the start of the string, or a preceding comma separator.
If we find such a match, it means that we found one or more numbers in the CSV list (or a single number, if only one number present) which had a leading zero.
$input = "00005,3";
if (preg_match("/\b0\d+/", $input)) {
echo "no match";
}

You can do a simple check that if the first character is 0 (using [0]) or that ,0 exists in the string
if ( $string[0] == "0" || strpos($string, ",0") !== false ) {
// One of them had leading zeros!
}

All the current answers fail if any of the values are simply 0.
You can just convert to integer and back and compare the result.
$arr = explode(',', $input);
foreach($arr as $item) {
if( (str)intval($item) !== $item ) {
oh_noes();
}
}
However I am more curious as to why this check matters at all.

One way would be with /^([1-9]+),(\d+)/; a regex that checks the string starts with one or more non-zero digits, followed by a comma, then one or more digits.
preg_match('/^([1-9]+),(\d+)/', $input_line, $output_array);
This separates the digits into two groups and explicitly avoids leading zeros.
This can be seen on Regex101 here and PHPLiveRegex here.

Related

Unable to make use of PHP regex matches

I have some PHP code that accepts an uploaded file from an HTML form then reads through it using regex to look for specific lines (in the case below, those with "Number" followed by an integer).
The regex matches the integers like I want it to, but of course they're returned as strings in $matches. I need to check if the integer is between 0 and 9 but I um unable to do this no matter what I try.
Using intval() or (int) to first convert the matches to integers always returns 0 even though the given string contains only integers. And using in_array to compare the integer to an array of 0-9 as strings always returns false as well for some reason. Here's the trouble code...
$myFile = file($myFileTmp, FILE_IGNORE_NEW_LINES);
$numLines = count($myFile) - 1;
$matches = array();
$nums = array('0','1','2','3','4','5','6','7','8','9');
for ($i=0; $i < $numLines; $i++) {
$line = trim($myFile[$i]);
$numberMatch = preg_match('/Number(.*)/', $line, $matches);
if ($numberMatch == 1 and ctype_space($matches[1]) == False) { // works up to here
$number = trim($matches[1]); // string containing an integer only
echo(intval($number)); // conversion doesn't work - returns 0 regardless
if (in_array($number,$nums)) { // searching in array doesn't work - returns FALSE regardless
$number = "0" . $number;
}
}
}
I've tried type checking, double quotes, single quotes, trimming whitespace, UTF8 encoding...what else could it possibly be? I'm about to give up on this app entirely, please save me.
Use '===' for eq for example
if 1 == '1' then true;
if 1 === '1' false;
if 1 == true then true;
if 1 === true then false
You can show file?
You write in your question that you're using a regular expression to look for the term "Number" followed by a single digit (0-9).
A regular expression for it would be:
/Number(\d)/
It will contain in the matching group 1 the number (digit) you're looking for.
The pattern you use:
/Number(.*)/
can contain anything (but a line-break) in the first matching group. It obviously is matching too much. You then have a problem filtering that too much retro-actively.
It normally works best to first look as precise as possible than to fiddle with too much noise afterwards.

Compare two digits elegant solution

I have the following two variables:
$addressphone='5612719999';
$googlephone='561-271-9999';
Is there an elegant solution in PHP that can validate that these two variables actually are equal. I'd prefer not to use str_replace as the conditions can change and I'd have to account for everything.
I've tried casting and intval but neither seemed to work
UPDATE
$addressphone='5612719999';
$googlephone='561-271-9999';
preg_replace("/\D/","",$googlephone);
var_dump($googlephone);
returns string(12) "561-271-9999"
I'm kind of reiterating what the comments say, but you should remove the non-digits from each string and them compare their integer values.
// original, non-integer-infested strings
$addressphone= "5612719999";
$googlephone= "561-271-9999";
// remove non-digits
$addressphone = preg_replace("/\D/","",$addressphone);
$googlephone = preg_replace("/\D/","",$googlephone);
and then you can check the following condition for equality:
// compare integer values of digit-only strings
intval($addressphone) == intval($googlephone)
// should return true
I would use preg_replace() to remove all non-numeric characters. That way, you're just working with numeric strings, which you can compare any way you'd like.
<?php
$testString = "123-456-7890";
echo preg_replace("/\D/", "", $testString); //echos 1234567890
?>
Try this :
print_r($addressphone === implode("", explode("-",$googlephone)))
$pieces = explode("-", $googlephone);
$newstring="";
foeach ($piece in $pieces)
{
$newstring +=piece;
}
Now compare your string with $newstring.
Remove everything that isn't a digit:
<?php
$addressphone ='5612719999';
$googlephone ='561-271-9999';
$number_wang = function($numberish) {
return preg_replace('/[^0-9]/', '', $numberish);
};
assert($number_wang($googlephone) == $addressphone);

Check if string is a comma-separated list of digits

In my table1 i have varchar field where i store an id-list of other table2 (id - INT UNSIGNED AUTOINCREMENT), separated by comma.
For example: 1,3,5,12,90
Also ids should not be repeated.
I need to check if a string (coming from outside) matches this rule.
For example i need to check $_POST['id_list']
Data consistency is not important for now (for example insert this value without checking if this ids really exist in table2)
Any advice will be helpful.
The easiest way to do such check is to use regular expression (preg_match).
Lets try to find a pattern matching our rule.
Just comma-separated digits:
^[0-9]+(,[0-9]*)*$
^ - means start of string.
$ - means end of string.
[0-9]+ - means that our string MUST starts with a digits.
(,[0-9]+)* - means that our string CAN continue itself with ",$someDigits" manner, from 0 to as many you wish times.
But if our digits are "INT UNSIGNED AUTOINCREMENT" we should modify our pattern this way:
^[1-9][0-9]*(,[1-9][0-9]+)*$
to exclude cases like: 0,01,02,009,000,012
As for unique values, i think more clear will be to use splitting (explode) string by comma to array, pass it through array_unique and compare.
So the result check-function will be:
function isComaSeparatedIds($string, $allowEmpty = false) {
if ($allowEmpty AND $string === '') {
return true;
}
if (!preg_match('#^[1-9][0-9]*(,[1-9][0-9]*)*$#', $string)) {
return false;
}
$idsArray = explode(',', $string);
return count($idsArray) == count(array_unique($idsArray));
}
Also added $allowEmpty argument if u would like to allow empty strings.
For the sake of completeness I would like to mention the following solution:
<?php
$check = explode(',', $string);
if ($diff = array_diff_key($check, array_filter($check, 'ctype_digit'))) {
// at least one is not a digit
foreach ($diff as $failIndex => $failValue) {
// handle
}
}
For less than 1000 digits in the string this is a little faster than preg_match and as little extra you get the positions and the values that are not a digit.
This is a bit of a cheeky solution,but it sure does the work.
<?php
$a="1,3,5,12,90";
$b=explode(",",$a);
$str='';
for($c=0;$c<count($b);$c++)
{
if (preg_match('/^[0-9]+$/', $b[$c]))
{
$str=$str."Y";
}
}
if(count(array_unique($b))==count($b) && (count($b)==strlen($str)))
{
echo $str;
//FURTHER CODE HERE WHEN ALL ELEMENTS UNIQUE AND VALID NUMBERS
}
else
{
//FURTHER CODE HERE WHEN NOT UNIQUE OR NOT A VALID NUMBERS
}
?>

How to check a string for a given format using PHP?

I have many headlines in my project like:
00.00.2014 - Headline Description e.t.c.
I want to check with php if the given strings contain the format 00.00.0000 - in front. The part after the - doesn't matter.
Can someone help me with something like:
$format = '00.00.0000 -';
if ($string MATCHES $format IN FRONT) {
// ...some code...
}
This should work:
if (preg_match("/^\d{2}\.\d{2}\.\d{4}\s\-\s.*$/", $string) === 1) {
// $string matches!
}
Explanation:
^ is "the beginning of the string"
\d is any digit (0, 1, 2, ..., 9)
{n} means "repeated n times"
\. is a dot
\s is a space
\- is a minus sign
. is "any single character"
* means "repeated 0 or more times`
$ means "end of the string"
I don't have a dev environment to test this out on but i'll give you some psuedocode:
I'm unsure of the context, but you can test this function on any given STRING:
Function:
Boolean hasCorrectFormat($myString){
//Here take the string and cut it into a char array.
$charArray = str_split($myString);
//This will give you a char array. Compare the first 12 elements of this
//array to see if they are correct. If its supposed to be number make
//sure it is, if its supposed to be a "." make sure it is..etc
//"00.00.0000 -" is 12 characters.
if(!isNumeric(charArray[0])){
return false;
}
else if(!isNumeric(charArray[1])){
return false;
}
else if(charArray[2] != "."){
return false;
}
//so on and so forth.....
else {return true}
}
Like i said i can't test this, and i can almost guarantee you this code wont run. This should give you the logic involved though.
Edit: also i wrote this assuming you dont literally mean "00.00.0000" but rather "xx.xx.xxxx" x being any number 0-9. If you need to make sure it is literally zeros then just cut your string to be the first ten chars and compare it.
Use the strpos function. Something like this:
if (strpos($string,'00.00.0000 -') !== true) {
//some code
}

php regex question - test 10 digits long with first 5 same digit and second 5 another

I'm trying to port this java to php:
String _value = '1111122222';
if (_value.matches("(1{5}|2{5}|3{5}|4{5}|5{5}|6{5}|7{5}|8{5}|9{5}){2}")) {
// check for number with the same first 5 and last 5 digits
return true;
}
As the comment suggests, I want to test for a string like '1111122222' or '5555566666'
How can I do this in PHP?
Thanks,
Scott
You can use preg_match to do so:
preg_match('/^(1{5}|2{5}|3{5}|4{5}|5{5}|6{5}|7{5}|8{5}|9{5}){2}$/', $_value)
This returns the number of matches (i.e. either 0 or 1) or false if there was an error. Since the String’s matches method returns only true if the whole string matches the given pattern but preg_match doesn’t (a substring suffices), you need to set markers for the start and the end of the string with ^ and $.
You can also use this shorter regular expression:
^(?:(\d)\1{4}){2}$
And if the second sequence of numbers needs to be different from the former, use this:
^(\d)\1{4}(?!\1)(\d)\2{4}$
Well, you could do:
$regex = '/(\d)\1{4}(\d)\2{4}/';
if (preg_match($regex, $value)) {
return true;
}
Which should be much more efficient (and readable) than the regex you posted...
Or, an even shorter (and potentially cleaner) regex:
$regex = '/((\d)\2{4}){2}/';
$f = substr($_value, 0, 5);
$s = substr($_value, -5);
return (substr_count($f, $f[0]) == 5 && substr_count($s, $s[0]) == 5);
Conversion is below. preg_match() is the key: http://www.php.net/preg_match
$value = '1111122222';
if (preg_match('/^(1{5}|2{5}|3{5}|4{5}|5{5}|6{5}|7{5}|8{5}|9{5}){2}$/', $value)) {
// check for number with the same first 5 and last 5 digits
return true;
}

Categories