duanrong5927 2013-02-18 19:47
浏览 19
已采纳

PHP搜索前/后获取文本

How would I go about turning my search results into something like this: http://i.stack.imgur.com/NfPGs.png

Where the results show where in the cell the particular term is.

I currently have this basic search script:

      $terms = explode("-", $SQuery);
    $QuerySQL = "SELECT * FROM pages WHERE ";

        foreach ($terms as $each){
        $i++;

        if ($i == 1)
            $QuerySQL .= "Title LIKE '%$each%' OR Content LIKE '%$each%' OR Description LIKE '%$each%'";
        else 
            $QuerySQL .= "OR Title LIKE '%$each%' OR Description LIKE '%$each%' OR Content LIKE '%$each%'";
        }

    $QueryNEW = mysql_query($QuerySQL);

WHILE($datarows_cat = mysql_fetch_array($QueryNEW)):

        $title = $datarows_cat['Title'];
        $Deleted = $datarows_cat['Deleted'];
        $id = $datarows_cat['ID'];
        if ($Deleted != "YES") {
        echo "<a href='/{$id}'>{$title}</a><br/>";

}
  • 写回答

1条回答 默认 最新

  • doujin8476 2013-02-18 19:58
    关注

    You can use PHP strpos to find +/- 100 characters:

    $pos = strpos($mystring, $findme);
    
    if ($pos === false) {
        echo "The string '$findme' was not found in the string '$mystring'";
    } else {
        echo "The string '$findme' was found in the string '$mystring'";
        echo " and exists at position $pos";
    }
    

    Then use PHP substr to get the substring of $pos+100 and $pos-100

    //For instance your substring could start at the position of the word found minus 100 characters and a length of 200
    $result = substr($mystring, $pos-100, 200);
    

    You can use PHP str_replace to format the string you need:

    $word_your_looking_for = "test";
    $word_you_want_to_replace_it_with = "<b>test</b>"; //Make it bold
    
    str_replace($word_your_looking_for, $word_you_want_to_replace_it_with, $your_string);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向