Jump to content

Recommended Posts

I am not sure why but my preg match fails and keeps setting quantity to zero every time.

 

Im trying to get it to only allow full integers only. Examples:

 

1 - correct

1.5 - not correct

+1 - not correct

-1 - not correct

f1 - not correct

etc

 

Why does it keep failing ?

 

<?php
$Quantity = 2;
If(!(preg_match('~^\d\+\.\-$~', $Quantity))){
   $Quantity = 0;
   }
Echo $Quantity;
?>

Link to comment
https://forums.phpfreaks.com/topic/134291-solved-preg-match-not-working/
Share on other sites

I don't think they do, try them out ?

Read the comments on the is_numeric page

From the comments

<?php
function my_is_numeric($value)  {
    $american = preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
    $world = preg_match ("/^(-){0,1}([0-9]+)(.[0-9][0-9][0-9])*([,][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
   return ($american or $world);
}
?>

Sorry, I just realized I overlooked some of my mistakes in my first reply, which now is tested and works in all cases (well, almost... not "+1 - not correct", how you see that is really different from "1" I'm not sure.):

<?php
if(!is_int($quantity) || $quantity<0) {
   $quantity = 0;
}
?>]

 

However, btherl, I ran your preg with the test cases and they failed. Still allows the decimals/negatives

Sorry, I just realized I overlooked some of my mistakes in my first reply, which now is tested and works in all cases (well, almost... not "+1 - not correct", how you see that is really different from "1" I'm not sure.):

<?php
if(!is_int($quantity) || $quantity<0) {
   $quantity = 0;
}
?>]

 

However, btherl, I ran your preg with the test cases and they failed. Still allows the decimals/negatives

 

I was concerned that something like 1+2 would be accepted  thus also allowing things like 1*4 etc which would change the value that went in.

 

But it is working now so thank you :) Works a tread.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.