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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?