English 中文(简体)
关于重点强调的飞行关键词
原标题:On the fly keyword highlighting
  • 时间:2012-01-14 15:56:08
  •  标签:
  • php
  • html
  • css

I have a PHP search script and I want to highlight the keywords that the user has searched with tags. How can I do this?

My code is:

if(!empty($_GET[ q ])){
$keywords=explode(   ,$_GET[ q ]);
foreach($keywords as $query){
$query=mysql_real_escape_string($query);
$likes[]="keywords LIKE  %{$query}% ";
}

$searchResult=mysql_query("select * from questions where ".implode( or  ,$likes)."limit 1");
while($row=mysql_fetch_assoc($searchResult)){
    $results="<div class= webresult >{$row[ result ]}</div>";
}
}
最佳回答

If $row[ result ] does not contain html, you can do a string replace: replace all keywords in the result with <span class="highlight">keyword</span>

简单的例子:

...
while($row=mysql_fetch_assoc($searchResult)) {
  $res = $row[ result ];
  foreach($keywords as $kw) {
    $res = str_replace($kw,  <span class="highlight">  . htmlspecialchars($kw) .  </span> , $res);
  }
  $results="<div class= webresult >{$res}</div>";
}
...
问题回答

两种解决办法,取决于结果是否含有超文本。

  1. 如果结果可能含有超文本,则使用前言。 参看 查询中的多重关键词

  2. If it can contain HTML, then you will need to use a DOM parser to separate text from HTML. Example parsers include Simple HTML Dom and DOMDocument.





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签