I'm trying to take four variables with a text value and a html form textbox to output which variables have which keyword in them. I've made a very brutal method and i'm quite new to PHP so i'm sure there is a much more efficient method so I thought it would be best to ask. This is the method I currently have, but of course it only works if I know what the variables are.
<?
$a = 'A = how are you today';
$b = 'B = how are you';
$c = 'C = how are';
$d = 'D = how';
if(isset($_POST["searchSub"])){
$search = $_POST['searchTb'];
if ($search == 'today'){
echo 'Results: <br>'.$a;
}
if ($search == 'you'){
echo 'Results: <br>'.$a.'<br>'.$b;
}
if ($search == 'are'){
echo 'Results: <br>'.$a.'<br>'.$b.'<br>'.$c;
}
if ($search == 'how'){
echo 'Results: <br>'.$a.'<br>'.$b.'<br>'.$c.'<br>'.$d;
}
}
?>
Instead of building a search form to check whether a particular word is within the search query, why not split the values that are being searched -- then you will know every word that is within that string. This can be done by using explode()
on the space:
if(isset($_POST["searchString"])) {
$words = explode(" ", $_POST["searchString"]);
}
This allows you to loop over each of the words in the string, and then check if it matches the desired text. In the following example, I do this with if (in_array())
:
$target = array("how", "are", "you", "today");
foreach ($words as $word) {
if (in_array($word, $target)) {
echo "Match: " . $word . "<br />" . PHP_EOL;
}
}
Combined, this would look like:
$target = array("how", "are", "you", "today");
if(isset($_POST["searchString"])) {
$words = explode(" ", $_POST["searchString"]);
foreach ($words as $word) {
if (in_array($word, $target)) {
echo "Match: " . $word . "<br />" . PHP_EOL;
}
}
}
Hope this helps! :)