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';
}
Related
The problem is with this line:
if $var LIKE '1800%';
and I'm not sure how to fix it. Thanks.
<?php
//check to see if account number is like 1800*
if (isset($_POST['acct_number'])) {
$var = $_POST['acct_number'];
if $var LIKE '1800%'; {
//stop the code
exit;
} else {
echo 'normal account number';
}
}
?>
You need PHP not MySQL. For 1800% just check that it is found at position 0:
if(strpos($var, '1800') === 0) {
//stop the code
exit;
} else {
echo 'normal account number';
}
If it can occur anywhere like %1800% then:
if(strpos($var, '1800') !== false) {
//stop the code
exit;
} else {
echo 'normal account number';
}
Use substr function to get first 4 characters and compare it with 1800.
if(substr($var, 0, 4) == '1800')
{
// your code goes here.
}
``
Another way could be to use strpos()
if (strpos($var, '1800') === 0) {
// var starts with '1800'
}
I would use a regular expression for this preg_match('/^1800.+/', $search, $matches);
Here is what I have tried but it is giving me wrong output. Can anyone point out what is the mistake?
function superPower($n) {
$response = false;
$n = abs($n);
if ($n < 2) {
$response = true;
}
for ($i=2;$i<$n;$i++) {
for ($j=2;$j<$n;$j++) {
if (pow($i,$j) == $n) {
$response = true;
}
}
}
return $response;
}
For example if I give it number 25, it gives 1 as output. //Correct
But if I give it 26 it still gives me 1 which is wrong.
By using superPower, you are essentially trying to put a certain defence to the power of an attack to see if it holds up. This can be done much more effectively than through the brute-force method you have now.
function superPower( $hp) { // Niet used Superpower!
if( $hp <= 1) return true;
for( $def = floor(sqrt($hp)); $def > 1; $def--) { // Niet's Defence fell
for( $atk = ceil(log($hp)/log($def)); $atk > 1; $atk--) { // Niet's Attack fell
if( pow($def,$atk) == $hp) return true;
break;
// you don't need the $atk loop, but I wanted to make a Pokémon joke. Sorry.
}
// in fact, all you really need here is:
// $atk = log($hp)/log($def);
// if( $atk-floor($atk) == 0) return true;
}
return false;
}
The maths on the accepted answer is absolutely brilliant, however there are a couple of issues with the solution:
the function erroneously returns true for all of the following inputs: monkey, -3 and 0. (Technically 0 is unsigned, so there is no way of getting it by taking a positive integer to the power of another positive integer. The same goes for any negative input.)
the function compares floating numbers with integers (floor() and ceil() return float), which should be avoided like the plague. To see why, try running php -r '$n = (-(4.42-5))/0.29; echo "n == {$n}\n".($n == 2 ? "OK" : "Surprise")."\n";'
The following solution improves on the idea by fixing all of the above issues:
function superPower($value)
{
// Fail if supplied value is not numeric
if (!is_numeric($value)) {
// throw new InvalidArgumentException("Value is not numeric: $value");
return false;
}
// Normalise numeric input
$number = abs($value);
// Fail if supplied number is not an integer
if (!is_int($number)) {
// throw new InvalidArgumentException("Number is not an integer: $number");
return false;
}
// Exit early if possible
if ($number == 1) {
// 1 to the power of any positive integer is one
return true;
} elseif ($number < 1) {
// X to the power of Y is never less then 1, if X & Y are greater then 0
return false;
}
// Determine the highest logarithm base and work backwards from it
for ($base = (int) sqrt($number); $base > 1; $base--) {
$coefficient = log($number)/log($base);
// Check that the result of division is a whole number
if (ctype_digit((string) $coefficient)) {
return true;
}
}
return false;
}
I used to rely on is_numeric() for making sure data passed from users is numeric. I recently discovered that users can also pass data 0xFF (hexdec = 255).
I'd like to disallow anything that is not a whole number (and not a hex representation).
Here's what I've tried so far.
$i_haxors_u = $_GET['id'];
$regex = '/[0-9]*/';
if (!empty($i_haxors_u) && !preg_match($regex, $i_haxors_u))
{
echo '<p>Invalid $i_haxors_u ' . strip_tags($i_haxors_u);
} else {
echo '<p>$i_haxors_u is numeric... maybe.';
}
This is still giving values like 0xFF a pass. How do I allow non-hex numbers only?
UPDATE Nov 12 2014.
Note that the selected answer works fine for data passed via GET, but will not work if a variable is set to a hex value.
$x = 0xFF;
if (is_numeric($x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
if (preg_match('/^[\d]+$/',$x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
$x = '0xFF';
if (is_numeric($x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
if (preg_match('/^[\d]+$/',$x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
Prints
255 is a number.
255 is a number.
0xFF is a number.
0xFF is not a number.
use match non-digit in your regex: $regex = '/\D/';
assume failure and pass when confirming that no non-digits are present in the input.
following code succeeds on id =7, give fail on id = 7.2, 7.2x, ffff, 0xff, -1
$id = $_GET['id'];
//assuming failure:
$valid = false;
if (!preg_match('/\D/',$id)) { $valid = true; } //fail if containing non-digit
if ($valid) {
echo "$id provided is valid";
}
else {
echo "$id provided is not valid";
}
You need to use anchors and use + quantifier to only allow integers:
$regex = '/^\d+$/';
Using + quantifier will also let you take out !empty($i_haxors_u) condition since \d+ will enforce 1 or more digits.
It's just because you have to test all the number:
$regex = '/^[0-9]+$/';
no need to test empty with +
How to compare 2 variable using php like this ?
$aaa = "1234567890qwertyuiopsdflkjwerouioiuweewjkee";
$bbb = "1234567890qwertyuiop";
How to check
if(first char to twenty char of $aaa == $bbb)
{ echo "same"; }
else
{ echo "not same"; }
I assume you are searching for strncmp:
This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison.
if(strncmp($aaa, $bbb, 20) == 0) {
# First twenty characters match.
} else {
# First twenty characters don't match.
}
$aaafirst20 = $small = substr($aaa, 0, 20);
if(strcmp($aaafirst20 , $bbb){
}
else{
}
Try this :
You can use strcmp function for the same.
PHP docs # strcmp
if(strcmp($aaa,$bbb)){
echo "same";
} else {
echo "not same";
}
You can use strpos() to check if $bbb is found in $aaa, and starts at position 0.
if (strpos($aaa, $bbb) === 0) {
echo 'Same';
}
else echo 'Not same';
See demo
Your exact solution would be
// first reduce a to its first 20 characters
$trimmed = substr($aaa, 0, 20);
// now compare with b
if($trimmed == $bbb){
// same
}
Or, all in one line
if(substr($aaa, 0, 20) == $bbb){
// same
}
i am trying this code for make a validation for a value. (regex from this site)
UPDATE:
Now i have
$value1=250;
$value2=10000;
if (!preg_match("/^(([^0]{1})([0-9])*|(0{1}))(\,\d{2}){0,1}€?$/", $form['salary']) || (!$form['salary'])>$value1."€" && (!$form['salary'])<$value2."€" ){
echo ("invalido");
return false;
}
else
echo ("valido");
return true;
the code works well, but 20€ is accepted, so the problem now is not the regex, but compare values like 200€ or 1000€.
this probably is wrong
(!$form['salary'])>$value1."€"
example some Input values:
200€
200
200.5
200.50€
limits - 250€ to 10000€
thanks
This code below solved my problem:
if (!preg_match("/^(([^0]{1})([0-9])*|(0{1}))(\,\d{2}){0,1}€?$/", $form['salary'])) {
echo "invalid";
return false;
} else {
$value1 = 400;
$value2 = 10000;
$salary = $form['salary'];
$salary = preg_replace('/[€]/i', '', $salary);
if($salary < $value1 || $salary > $value2) {
echo "bad values";
return false;
} else {
echo "valid";
return true;
}
}
The regex solution would look like this
^(?:10000|(?:(?:(?:2[5-9]\d)|[3-9]\d{2}|\d{4})(?:[,.]\d{2})?))€?$
See here online on Regexr
But it would be better for checking if a value belongs to a range, not to use a regex. You can extract the value easily and do a normal <> check on numbers outside.
My contribution. It works great.
final Pattern pattern = Pattern.compile("^([0-9]+)|((([1-9][0-9]*)|([0-9]))([.,])[0-9]{1,2})$");