dongleiqiao2107 2011-09-06 10:53
浏览 36
已采纳

Php mysql搜索脚本,如果搜索词与我的数据库条目不完全匹配,如何使单个搜索词变为粗体

Below is my script so far. This displays the users search term in bold if it is an exact match. For example. if the user searched "john bloggs" then it would be returned bold. whereas if the user searched for "john" then it would show the john bloggs entry but it wouldnt be in bold. Any help would be greatly appreciated.

<?
mysql_connect ("localhost", "user","pass")  or die (mysql_error());
mysql_select_db ("databasename");

$term = $_POST['term'];

$sql = mysql_query("select * from tablename where category like '%$term%' or title like '%$term%' or postcode like '%$term%' or info like '%$term%' ");

while ($row = mysql_fetch_array($sql)){

    echo '<br/> Category: '.str_replace($term,'<b>'.$term.'</b>',$row['category']);
    echo '<br/> Title:    '.str_replace($term,'<b>'.$term.'</b>',$row['title']);
    echo '<br/> Address:  '.$row['add1'];
    echo '<br/> Street:   '.$row['street'];
    echo '<br/> City:     '.$row['city'];
    echo '<br/> Postcode: '.str_replace($term,'<b>'.$term.'</b>',$row['postcode']);
    echo '<br/> Phone:    '.$row['phone'];
    echo '<br/> E-Mail:   '.$row['email'];
    echo '<br/> Website:  '.$row['website'];
    echo '<br/><br/>';

}
?>
  • 写回答

4条回答 默认 最新

  • douzepao0281 2011-09-06 11:50
    关注

    I'm using the following:

    /**
     * higlights search string with HTML5-mark
     *
     * @param string needle search string
     * @param string haystack original text, may contain search string
     * @return string original text with additional HTML-mark highlighting
     */
    function highlight($needle, $haystack)
    {
        return preg_replace('/(' . preg_quote($needle, '/') . ')/i', '<mark>$1</mark>', $haystack);
    }
    

    Usage:

    echo '<br/> Category: ' . highlight($term, $row['category']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器