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>';
}
}
?>
I’d do something like this:-
So loop over the list of strings to search, set a flag (
$match), then for every word in the$stringcheck it exists somewhere in the current$listOfSearchesstring, if a word doesn’t exist it will set the$matchto false.After checking for every word, if the
$matchis stilltrue, add to the current string from$listOfSearchesto the$matchesarray.