P-nut
06-24-2008, 05:11 PM
I know the answer for this must be pretty simple but I'm just not having much luck finding what I need.
I have a PHP script with a form and a text file containing a bunch of keywords/phrases. I want to, upon the form submission, open the text file and search it to see if the contents of one of the fields match a phrase in the text file. The phrases are separated in the text file by returns (ie, one phrase per line)
I'm pretty sure I'd use something like fopen to open the text file, but I have no clue where to go from there. :confused: Any help is always appreciated! :)
Jamie Edwards
06-24-2008, 06:08 PM
http://uk2.php.net/file_get_contents
http://uk.php.net/strpos
Would be what I'd use :)
111111z
06-24-2008, 06:16 PM
test code will search in the string $a for 12
and return the found string position if found
<?php
$a="data 12345";
$i=strpos($a,"12");
if($i===FALSE)
echo "not Found";
else
echo "Found at Position $i";
?>
because PHP rulez
P-nut
06-24-2008, 08:13 PM
I've tried file_get_contents with strpos and was unable to get it to work.
I then tried this:
$q=0; //q indicates a match
$i=0; //i indicates no match
$string = "this is fun. php.net. blah blah blah.";
$lines = file("path/to/myfilename.txt"); // To put the file contents into an array, so each phrase can be read
foreach($lines as $line_num => $line):
if(strpos($string,$line) === false): //also tried switching $line and $string, also tried stripos for case-insensitive search
$i++;
else:
$q++;
endif;
endforeach;
echo "Phrases Matched: ".$q."<br />";
echo $i." phrases did not match";
$string should have had 2 phrase matches, but continues to show as 0. :confused:
111111z
06-24-2008, 08:58 PM
just change the if statement to this
if(strpos($string,trim($line)) === false): //also tried switching $line and $string, also tried stripos for case-insensitive search
that should work
I think the reason why is because the CR LF from the file is making it not match...
trim removes them..
P-nut
06-24-2008, 09:15 PM
thanks so much 111111z! :beer: the trim did the trick and now returned the proper number of matches :) now my code looks like this:
$q=0; //q indicates a match
$i=0; //i indicates no match
$string = "this is fun. php.net. blah blah blah.";
$lines = file("path/to/myfilename.txt"); // To put the file contents into an array, so each phrase can be read
foreach($lines as $line_num => $line):
if(strpos($string,trim($line)) === false):
$i++;
else:
$q++;
endif;
endforeach;
echo "Phrases Matched: ".$q."<br />";
echo $i." phrases did not match";
111111z
06-24-2008, 09:29 PM
No Problem I have run into that same problem before that the cr lf
is screwing things up....
:)
php rulez