I need to verify that my string $path contains exactly 8 characters and that $path is in the following pattern: A000AA00 where A is any letter A-Z and 0 is any number 0-9.
The first thing I did was that I used strlen to get the string length.
if (strlen($path) !== 8) { die('Bad string length'); }
Next I used ctype_alpha and ctype_digit to check if the string is in the format I want based on what I expect $path[0-7] to be.
if (ctype_alpha($path[0]) && ctype_digit($path[1]) && ctype_digit($path[2]) && ctype_digit($path[3]) && ctype_alpha($path[4]) && ctype_alpha($path[5]) && ctype_digit($path[6]) && ctype_digit($path[7])) { // We good }
Could I improve this code somehow?
Are there any faster alternatives?
If you plan to use a regex to validate such a pattern, you may try
preg_match('~^[A-Z]\d{3}[A-Z]{2}\d{2}\z~', $s)
The regex approach is very readable: start with an uppercase letter, 3 digits, 2 uppercase letters, 2 digits, end of the string.
Now,
$path = "A000AA00";
$startA = microtime(true);
for($i = 0; $i < 100000; $i++)
{
if (strlen($path) !== 8) { die('Bad string length'); }
if (ctype_alpha($path[0]) && ctype_digit($path[1]) && ctype_digit($path[2]) && ctype_digit($path[3]) && ctype_alpha($path[4]) && ctype_alpha($path[5]) && ctype_digit($path[6]) && ctype_digit($path[7])) { // We good
}
}
$endA = microtime(true);
echo $endA-$startA;
yields 0.02226710319519 (PHP 7.3.2), and the regex based solution yields 0.0064888000488281.
I need a way to be able to automatically add a '0' in front of any number if the number a user enters is a number between 1-9 in PHP. I need this because I am trying to make a 10 character date so that I can search for exercises added to my website between the dates.
The easiest way to do this I thought was to start with a year, then the month, then the day so I get something like this: 2001/04/15. I can just have the user manually add a '0', but I was hoping there was a way to do that automatically.
So far, I have this, but it doesn't work quite right. Can someone help me out here?
Thanks in advance.
//Checks to see if start day is a number 1-9
//If so, adds a '0' at the beginning of the start day variable
if($_POST['eday'] == 1 || $_POST['eday'] == 2 || $_POST['eday'] == 3 || $_POST['eday'] == 4 ||
$_POST['eday'] == 5 || $_POST['eday'] == 6 || $_POST['eday'] == 7 || $_POST['eday'] == 8 ||
$_POST['eday'] == 9) {
$_POST['eday'] = 0 . $_POST['eday'];
echo $_POST['eday'] . '<br>';
}
Use printf formatting:
printf("%02d<br>", $_POST['eday']);
You are complicating yourself for nothing dude, you could do it like that :
if($_POST['eday'] < 10) $number = '0'.$_POST['eday'];
else $number = $_POST['eday'];
Here is another thing: http://www.w3schools.com/php/func_string_str_pad.asp
pad_str($str,20,".");
will pad out to 20 characters of "."
There is and optional 4th parameter.
STR_PAD_BOTH
STR_PAD_RIGHT (Default if not supplied)
STR_PAD_LEFT
so for you:
$str = $_POST['eday'];
pad_str($str,2,"0", STR_PAD_LEFT);
Now $str is set and you can use it where ever you need.
I am new to PHP. My problem is I need the input to validate to a minimum 20 character input and return the last nine. Can anybody tell me if my argument is close to working and if not what do I need to do?
if (!empty($_POST['usen']) ||
strlen($usen['usen'] >= 20 )) {
$switch = substr($usen, -9, 9); // returns last nine of sentence
$output_form=false;
} else {
$error_text .="<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form=true;
}
You have several syntax problems and variable-naming problems. Your code should be:
if (!empty($_POST['usen']) && // || should be &&; the || doesn't make sense here
strlen($_POST['usen']) >= 20 ) { // You had $usen['usen'] and an incorrectly placed )
$switch = substr($_POST['usen'], -9); // again, this should be $_POST['usen'], not $usen. The third parameter is unnecessary here.
$output_form = false;
} else {
$error_text .= "<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form = true;
}
The key points:
You're using the wrong boolean operator. !empty($x) || strlen($x) >= 20 doesn't make sense. It should be &&, not ||. If you have a non-empty value for $_POST['usen'], then !empty($_POST['usen']) is true. But because you had a || in your if conditional, this meant the if block always executed for non-empty values, never the else block. You only want the if to execute if the value is non-empty and at least 20 characters.
Your variable is $_POST['usen'], but your code referred to $usen['usen'] and $usen, which are incorrect.
You had strlen($usen['usen'] >= 20) where you should have strlen($_POST['usen']) >= 20. Both the variable name and the ) placement were incorrect.
To get the last 9 characters of $usen['usen'] use
$switch = substr($usen, -9);
if (!empty($_POST['usen']) ||
strlen($_POST['usen']) >= 20 ) { // changed condition
$switch = substr($usen, -9, 9); // returns last nine of sentence
$output_form=false;
} else {
$error_text .="<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form=true;
}
The if-condition has two issues in second part
You use $usen['usen'] but i think it schould be $_POST['usen'] (see also comment by #Ed Cottrell)
The closing bracker from method-call strlen has to be after the param
if (!empty($_POST['usen']) &&
strlen($_POST['usen'] )>= 20 ) { //condition change
$switch = substr($_POST['usen'] ,-9); // returns last nine of sentence
$output_form=false;
} else {
$error_text .="<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form=true;
}
To get last 9 charcters , you can use substr(string, -9);
This question already has answers here:
Checking string length with strlen
(3 answers)
Closed 9 years ago.
I want to add 2 numbers in the strlen command. here is my php code:
$name = mysql_real_escape_string($_POST['dgt']);
if(strlen($name) != "32") {
print "This is not a name.";
} else {
It checks if the length is 32. I want it to check if the length is 32 OR 40. how can I do that?
First of all, don't use mysql_real_escape_string(); the old mysql_ API is deprecated, so consider switching to PDO or mysqli instead.
Second, you should consider using input filtering; $_POST['dgt'] may not exist at all, so use filter_input().
Third, you should use numeric values to compare against the output of strlen(); although PHP will treat "32" as a number, it's better to be explicit.
Lastly, if a name must be either 32 or 40 long, you can simply add the condition:
$name = filter_input(INPUT_POST, 'dgt', FILTER_UNSAFE_RAW);
if (empty($name) || (strlen($name) != 32 && strlen($name) != 40)) {
print "This is not a name.";
}
Alternatively, use in_array():
if (empty($name) || !in_array(strlen($name), array(32, 40))) {
print "This is not a name.";
}
Use the and operator "&&" in your conditional, like the code below.
if(strlen($name) != 32 && strlen($name) != 40)
If you would like it to check if name is length 32 or 40 then use the or operator "||" like the code below.
if(strlen($name) == 32 || strlen($name) == 40)
user2910265 has a good point, assign the return value of strlen() to a variable so that only one call is made, like so.
$length = strlen($name);
if(!($length == 32 || $length == 40))
print "this is not a name.";
} else {
From the PHP: Logical Operators - Manual, you want to use either
or
|| (this form has higher precedence)
$a or $b Or TRUE if either $a or $b is TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
So, you could use something like this
$len = strlen($name); // just get the length once and then
// use it to compare however many times....
if (!($len == 32 or $len == 40))
I need to check for a form input value to be a positive integer (not just an integer), and I noticed another snippet using the code below:
$i = $user_input_value;
if (!is_numeric($i) || $i < 1 || $i != round($i)) {
return TRUE;
}
I was wondering if there's any advantage to using the three checks above, instead of just doing something like so:
$i = $user_input_value;
if (!is_int($i) && $i < 1) {
return TRUE;
}
Not sure why there's no suggestion to use filter_var on this. I know it's an old thread, but maybe it will help someone out (after all, I ended up here, right?).
$filter_options = array(
'options' => array( 'min_range' => 0)
);
if( filter_var( $i, FILTER_VALIDATE_INT, $filter_options ) !== FALSE) {
...
}
You could also add a maximum value as well.
$filter_options = array(
'options' => array( 'min_range' => 0,
'max_range' => 100 )
);
Learn more about filters.
the difference between your two code snippets is that is_numeric($i) also returns true if $i is a numeric string, but is_int($i) only returns true if $i is an integer and not if $i is an integer string. That is why you should use the first code snippet if you also want to return true if $i is an integer string (e.g. if $i == "19" and not $i == 19).
See these references for more information:
php is_numeric function
php is_int function
The best way for checking for positive integers when the variable can be INTEGER or STRING representing the integer:
if ((is_int($value) || ctype_digit($value)) && (int)$value > 0 ) { // int }
is_int() will return true if the value type is integer. ctype_digit() will return true if the type is string but the value of the string is an integer.
The difference between this check and is_numeric() is that is_numeric() will return true even for the values that represent numbers that are not integers (e.g. "+0.123").
It's definitely heading towards the land of micro-optimisation, but hey: the code I'm working on chews through millions of items every day and it's Friday. So I did a little bit of experimenting...
for ($i = 0; $i < 1000000; $i++) {
// Option 1: simple casting/equivalence testing
if ((int) $value == $value && $value > 0) { ... }
// Option 2: using is_int() and ctype_digit(). Note that ctype_digit implicitly rejects negative values!
if ((is_int($value) && $value > 0) || ctype_digit($value)) { ... }
// Option 3: regular expressions
if (preg_match('/^\d+$/', $value)) { ... }
}
I then ran the above tests for both integer and string values
Option 1: simple casting/equivalence testing
Integer: 0.3s
String: 0.4s
Option 2: using is_int() and ctype_digit()
Integer: 0.9s
String: 1.45s
Option 3: regular expressions
Integer: 1.83s
String: 1.60s
Perhaps unsurprisingly, option 1 is by far the quickest, since there's no function calls, just casting. It's also worth noting that unlike the other methods, option 1 treats the string-float-integer value "5.0" as an integer:
$valList = array(5, '5', '5.0', -5, '-5', 'fred');
foreach ($valList as $value) {
if ((int) $value == $value && $value > 0) {
print "Yes: " . var_export($value, true) . " is a positive integer\n";
} else {
print "No: " . var_export($value, true) . " is not a positive integer\n";
}
}
Yes: 5 is a positive integer
Yes: '5' is a positive integer
Yes: '5.0' is a positive integer
No: -5 is not a positive integer
No: '-5' is not a positive integer
No: 'fred' is not a positive integer
Whether or not that's a good thing for your particular use-case is left as an exercise for the reader...
The other best way to check a Integer number is using regular expression. You can use the following code to check Integer value. It will false for float values.
if(preg_match('/^\d+$/',$i)) {
// valid input.
} else {
// invalid input.
}
It's better if you can check whether $i > 0 too.
preg_match('{^[0-9]*$}',$string))
and if you want to limit the length:
preg_match('{^[0-9]{1,3}$}',$string)) //minimum of 1 max of 3
So pisitive int with a max length of 6:
if(preg_match('{^[0-9]{1,6}$}',$string)) && $string >= 0)
You don't really need to use all three check and if you want a positive integer you might want to do the opposite of what is in your code:
if(is_numeric($i) && $i >= 0) { return true; }
Check Sören's answer for more information concerning the difference between is_int() and is_numeric()
if(preg_match('/^[1-9]\d*$/',$i)) {
//Positive and > 0
}
Rather than checking for int OR string with multiple conditions like:
if ( ctype_digit($i) || ( is_int($i) && $i > 0 ) )
{
return TRUE;
}
you can simplify this by just casting the input to (string) so that the one ctype_digit call will check both string and int inputs:
if( ctype_digit( (string)$i ) )
{
return TRUE;
}
In addition to all the other answers: You are probably looking for ctype_digit. It looks for a string containing only digits.
Definition:
!A = !is_numeric($i)
B = $i < 1
!C = $i != round($i)
Then...
!is_numeric($i) || $i < 1 || $i != round($i) is equal to
!A || B || !C
So:
!A || B || !C = !A || !C || B
Now, using the deMorgan theorem, i.e. (!A || !C) = (A && C), then:
!A || !C || B = (A && C) || B
Now, note that A && C = is_numeric($i) && $i == round($i), but if $i == round($i) is TRUE, then is_numeric($i) is TRUE as well, so we can simplify A && C = C so,
(A && C) || B = C || B =
$i == round($i) || $i < 1
So you just need to use:
$i = $user_input_value;
if ($i == round($i) || $i < 1) {
return TRUE;
}
Laravel 4.2 Validation rule for positive number
It takes only positive numbers including float values.
public static $rules = array(
'field_name' => 'required|regex:/^\d*\.?\d*$/'
);
e.g:20,2.6,06
The first example is using round to verify that the input is an integer, and not a different numeric value (ie: a decimal).
is_int will return false if passed a string. See the PHP manual examples for is_int
To check for positive integer use:
$i = $user_input_value;
if (is_int($i) && $i > 0) {
return true; //or any other instructions
}
OR
$i = $user_input_value;
if (!is_int($i) || $i < 1) {
return false; //or any other instructions
}
Use the one that fits your purpose as they are the same. The following examples demonstrate the difference between is_numeric() and is_int():
is_numeric(0); // returns true
is_numeric(7); // returns true
is_numeric(-7); // returns true
is_numeric(7.2); // returns true
is_numeric("7"); // returns true
is_numeric("-7"); // returns true
is_numeric("7.2"); // returns true
is_numeric("abc"); // returns false
is_int(0); // returns true
is_int(7); // returns true
is_int(-7); // returns true
is_int(7.2); // returns false
is_int("7"); // returns false
is_int("-7"); // returns false
is_int("7.2"); // returns false
is_int("abc"); // returns false
All these answers overlook the fact that the requestor may checking form input.
The is_int() will fail because the form input is a string.
is_numeric() will be true also for float numbers.
That is why the $i == round($i) comes in as it checks for the input being a whole number.
Ok, I know this thread is really old but I share #Jeffrey Vdovjak's opinion: since I was able to find it, it might still help someone else out there.
php's gmp_sign() might be another easy way to check. It works for integer and numeric strings, and returns 1 if a is positive, -1 if a is negative, and 0 if a is zero.
So:
// positive
echo gmp_sign("500") . "\n";
// negative
echo gmp_sign("-500") . "\n";
// zero
echo gmp_sign("0") . "\n";
will output:
1
-1
0
See function manual at http://php.net/manual/en/function.gmp-sign.php
P.S. You'll need to have php_gmp.dll enabled in your .ini file.
This's my solution, hope helpful :
if (is_numeric($i) && (intval($i) == floatval($i)) && intval($i) > 0)
echo "positive integer";
i check if string is numeric, second check to sure it's integer and third to sure it positive
If you use "is_int" the variable must be integer, so it can't be a float value. (no round needed).
if(isset($i) && is_int($i) && $i >= 0){ //0 is technically a postive integer I suppose
return TRUE; //or FALSE I think in your case.
}
I would do something like this:
if ((int) $i > 0) {
// this number is positive
}
The number gets typecast to a positive or negative number depending on the minus sign being at the front. Then compares the typecast number to being greater than 0 to determine if the number is positive.