Jump to content

[SOLVED] preg match not working


EchoFool

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.