如何在php mysql搜索中加粗关键字?

时间:2010-10-12 03:17:13

标签: php javascript mysql ajax

当我搜索像

这样的关键字时,我希望我的输出像这样

“编程”

php 编程语言

如何在php mysql中执行此操作?

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

只需对返回的文本执行str_replace。

$search = 'programming';
// $dbContent = the response from the database

$dbContent = str_replace( $search , '<b>'.$search.'</b>' , $dbContent );

echo $dbContent;

任何“编程”实例,即使作为较大单词的一部分,也会包含在<b>标记中。

对于使用多个单词的情况

$search = 'programming something another';
// $dbContent = the response from the database

$search = explode( ' ' , $search );
function wrapTag($inVal){
  return '<b>'.$inVal.'</b>';
}
$replace = array_map( 'wrapTag' , $search );

$dbContent = str_replace( $search , $replace , $dbContent );

echo $dbContent;

这会将$search拆分为空格中的数组,然后将每个匹配包装在<b>标记中。

您可以使用<b><strong>代码(请参阅What's the difference between <b> and <strong>, <i> and <em>?了解相关内容)。

答案 1 :(得分:2)

$search = @$_GET['q'];
$trimmed = trim($search);

function highlight($req_field, $trimmed)  //$req_field is the field of your table
{
        preg_match_all('~\w+~', $trimmed, $m);
        if(!$m)
            return $req_field;
        $re = '~\\b(' . implode('|', $m[0]) . ')\\b~';
        return preg_replace($re, '<b>$0</b>', $req_field);
}

  print highlight($req_field, $trimmed);

通过这种方式,您可以加入搜索到的关键字。它非常简单,效果很好。

答案 2 :(得分:0)

响应实际上比这复杂一点。在常见的搜索结果用例中,还有其他因素需要考虑:

  • 你应该考虑大写和小写(编程,编程,编程等);
  • 如果你的内容字符串很长,你不会想要返回整个文本,而只是返回搜索到的查询以及它之前和之后的几个单词,用于上下文;

This guy弄清楚了:

//$h = text
//$n = keywords to find separated by space
//$w = words near keywords to keep

function truncatePreserveWords ($h,$n,$w=5,$tag='b') {
    $n = explode(" ",trim(strip_tags($n))); //needles words
    $b = explode(" ",trim(strip_tags($h))); //haystack words
    $c = array();                       //array of words to keep/remove
    for ($j=0;$j<count($b);$j++) $c[$j]=false;
    for ($i=0;$i<count($b);$i++) 
        for ($k=0;$k<count($n);$k++) 
            if (stristr($b[$i],$n[$k])) {
                $b[$i]=preg_replace("/".$n[$k]."/i","<$tag>\\0</$tag>",$b[$i]);
                for ( $j= max( $i-$w , 0 ) ;$j<min( $i+$w, count($b)); $j++) $c[$j]=true; 
            }   
    $o = "";    // reassembly words to keep
    for ($j=0;$j<count($b);$j++) if ($c[$j]) $o.=" ".$b[$j]; else $o.=".";
    return preg_replace("/\.{3,}/i","...",$o);
}

像魅力一样!