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

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

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.