Multiple search word matching using strpos

2020-04-21 02:14发布

问题:

I wonder if anyone can help with a little problem I can't seem to fix - my head is going round in circles at the moment...

Ok I have a .txt file with numerous lines of info - I am trying to match keywords with those lines and display a certain number of the matching lines.

I put together this bit of script and whilst it works it only matches a line if the words are in the same order as the search words.

At the moment as an example:

Search words:

red hat

Lines in .txt file:

this is my red hat
my hat is red
this hat is green
this is a red scarf
your red hat is nice

As the script is at the moment it will match and display lines 1, 5

However I would like it to match and display lines 1, 2, 5

Any order but all words must be present to match.

I have looked through loads of postings here and elsewhere and I understand that what is needed is to explode the string and then search for each word in a loop but I cannot get that to work, despite trying a few different ways as it just returns the same line numerous times.

Any help would be appreciated before I lose what hair I have left :-)

Here is the code I have working at present - the search variable is already set:

<?php
rawurldecode($search);
$search = preg_replace('/[^a-z0-9\s]|\n|\r/',' ',$search);
$search = strtolower($search);
$search = trim($search);

$lines = file('mytextfile.txt') or die("Can't open file");
shuffle($lines);

$counter = 0;

// Store true when the text is found
$found = false;

foreach($lines as $line)
 {

  if(strpos($line, $search) !== false AND $counter <= 4)
  {
    $found = true;
    $line = '<img src=""> <a href="">'.$line.'</a><br>';


    echo $line;
    $counter = $counter + 1;

  }

}

// If the text was not found, show a message
if(!$found)
{
  echo  $noresultsmessage;
}

?>

Thanks in advance for any help - still learning :-)

回答1:

Here's my code:

$searchTerms = explode(' ', $search);
$searchCount = count($searchTerms);
foreach($lines as $line)
 {
    if ($counter <= 4) {
        $matchCount = 0;
        foreach ($searchTerms as $searchWord) {
            if (strpos($line, $searchWord) !== false ) {
                $matchCount +=1;
            } else {
                //break out of foreach as no need to check the rest of the words if one wasn't found
                continue; 
            }
        }
        if ($matchCount == $searchCount) {
            $found = true;
            $line = '<img src=""> <a href="">'.$line.'</a><br>';
            echo $line;
            $counter = $counter + 1;
        }

    }
}


标签: php strpos