Jump to content

using preg_match regex with a variable input


glompt

Recommended Posts

Hi.  I need some help getting my preg_match regex working with a variable input.  I'm trying to limit visits to once per day, after you come the first time, you are added to data.txt and will be denied if you come again.  The code works, but I need to limit the searches using ^ and $ and I'm having some difficulty.

 

$number will be a number input from an html form ranging from 1-1000+ and I want to make sure that 1,10,100 etc., aren't treated as the same.

 

here is my preg_match, how do I use regular expressions with $number?

preg_match("/$number/", $file, $match) 

 

 

from what I have read, it should be like this, but it doesn't work

preg_match('/^+$' , "/$number/", $file, $match) 

 

 

heres the full code

$filename = "data.txt";     
$handle = fopen($filename, "r");  
$file = fread($handle,filesize($filename));  
if (preg_match("/$number/", $file, $match)) {      
    
echo " Sorry, Already visited today";

exit; 
}  
else { 
fclose($file);
  $file=fopen(data.txt,"a") or exit("Unable to open file!");
  fwrite($file, "$number");
  fwrite($file, "\n");
  fclose($file);
  echo " Accepted!";

exit; 
}  

 

 

 

 

Thanks

hi, thanks for the reply.

 

I'm using the preg_match in an if statement statement and changed it to reflect what you suggested:

if (preg_match('/^' . $number . '$/', $file, $match)) {  

 

However; using this causes the preg_match to always return false.  Any idea why?  Thanks again.

 

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.