Search code examples
phpstrpos

Unable to make a 'related terms' code using strpos work in PHP


What I'm trying to do is get an input text from the user (for example lets say 'Java programmer') and trying to match this user input with a list of strings that I have stored in an array like 'Java programmer is a good boy', 'he plays ball at times', 'java and dogs hate each other', ' dogs are not java programmers'

I'm trying to do word matching so the program outputs a list of all strings in the array that match all words in user query (order isn't important)

So I want the output of the below code to be...

'Java programmer is a good boy' 'dogs are not java programmers'

Because these terms contain both 'java' and 'programmers' as per the query the user enters

Here's the code I wrote, it doesn't work. Any help will be much appreciated.

<?php
$relatedsearches = array();
$querytowords = array();
$string = "Java programmer"; //GET INPUT FROM USER
$querywords = (explode(' ', $string));
foreach($querywords as $z)
    {
            $querytowords[] = $z;
            }

//ARRAY THAT STORES MASTER LIST OF QUERIES

$listofsearhches = array('Java programmer is a good boy', 'he plays ball at times', 'java and dogs hate each other', ' dogs are not java programmers');

foreach($listofsearhches as $c)
    {
    for ($i=0; $i<=(count($querytowords)-1); $i++)
        {   
        if(strpos(strtolower($c), strtolower($querytowords[$i])) === true)
            { 
            if($i=(count($querytowords)-1))
                {
                $relatedsearches[] = $c;
                } 
            } else { break; }
        }
    }

echo '<br>';
if(empty($relatedsearches))
    {
        echo 'Sorry No Matches found';
    } 
    else 
    {
    foreach($relatedsearches as $lister)
        {
                echo $lister;
                echo '<br>';
                }
            }

?>

Solution

  • I'd do something like this:-

    $matches = array();
    $string = 'java programmer';
    $stringBits = explode(' ', $string);
    $listOfSearches = array('Java programmer is a good boy', 'he plays ball at times', 'java and dogs hate each other', ' dogs are not java programmers');
    
    foreach($listOfSearches as $l) {
      $match = true;
      foreach($stringBits as $b) {
        if(!stristr($l, $b)) {
          $match = false;
        }
      }
      if($match) {
        $matches[] = $l;
      }
    }
    
    if(!empty($matches)) {
      echo 'matches: ' . implode(', ', $matches);
    } else {
      echo 'no matches found';
    }
    

    So loop over the list of strings to search, set a flag ($match), then for every word in the $string check it exists somewhere in the current $listOfSearches string, if a word doesn't exist it will set the $match to false.

    After checking for every word, if the $match is still true, add to the current string from $listOfSearches to the $matches array.