doushu5451
2017-09-03 22:58
浏览 11
已采纳

简化搜索关键字方法的文本变量PHP [关闭]

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;
    }
}
?>
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanboxue3422 2017-09-03 23:16
    已采纳

    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! :)

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题