View Full Version : string comparison

07-14-2008, 10:15 AM

i am writing a small application where a user enters a phrase in the textfield and i would like to display all the files

present in the root directory which consists of the keyword or keywords entered by the user.

i have used a few comparison functions but i am not getting the expected result.

$my_file = file_get_contents("filename.html");
what ever the user enters whether it is a single word or few words i would like to compare with $my_file in a case

insensitive manner.

can anyone suggest the best method and how to go about.


07-14-2008, 10:28 AM
Pattern matching is the best route to use. I don't know what format you'll allow, but I will say its a single text entry line separated with spaces. This example (though untested) will try to scan only a single directory and is not built for recursion.

$keywords = str_replace(' ', '\'|\'', $inputKeywords);
$matches = array();
foreach (glob('*') AS $file)
if (is_file($file))
$sFileContents = file_get_contents($file);
if (preg_match('/\'[' . $keywords . ']\'/msi', $sFileContents))
$matches[] = $file;

I don't know if something like this will work, but off hand it looks like it should do the job. $inputKeywords is whatever you're entry is, including whatever cleaning you need to do to it.

07-14-2008, 11:30 AM
Check out strcmp (http://uk2.php.net/manual/en/function.strcmp.php)and strcasecmp (http://uk2.php.net/manual/en/function.strcasecmp.php) to perform both sensitive and insensitive string comparisons.

Fou-Lu has shown how to perform this operation using regular expressions, which is handy in the event that you want to continue searching if a user miss typed keywords etc.