Jump to content

if statement preg_match help


glompt

Recommended Posts

Hi.  I'm trying to write a little php script that will take an input number from a text field and check it against a text file to see if it is already there, if it is it says so, if not, it adds it to the list.  Where i'm having issues is with defining my regex; more specifically, I want it to handle 110 and 11 differently. 

 

Here is my current code so far that works:

 

<html><body>
<h4>DT</h4>


<form action="test.php" method="post"> 
ID#: <input name="number" type="text" /> 
<input type="submit" />
</form>

<?php
$number = $_POST['number'];


echo "$number";



//search

$filename = "dtdatatxt";     
$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(dtdata.txt,"a") or exit("Unable to open file!");
  fwrite($file, "$number");
  fwrite($file, "\n");
  fclose($file);
  echo " Accepted!";


exit; 

}  


?>
</body></html>

 

If I'm not mistkaken, the correct preg_match statement should be

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

However, when I use this statement, it always returns false.

 

Any ideas?

 

Thanks

 

 

Link to comment
https://forums.phpfreaks.com/topic/224887-if-statement-preg_match-help/
Share on other sites

That will only work if that number is the only thing in the entire file, with no leading or trailing spaces and no line break at the end. Put a else on that, to output $file to see what the actual contents are, if you can't match it, that way you can fine out why

Use the m pattern modifier with your existing regex.

 

P.S. Life would be easier if you also used the file_get/put_contents functions.

 

http://php.net/reference.pcre.pattern.modifiers

http://php.net/file_get_contents

http://php.net/file_put_contents

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.