【发布时间】:2014-10-08 14:34:13
【问题描述】:
我正在为我的框架创建一个基本的搜索功能,并寻找一些关于如何以最佳方式(谷歌风格)显示搜索结果的建议。我的 MYSQL 查询根据搜索查询返回不同的页面。从 MySQL 返回的结果是完美的,我只需要执行以下操作:
例如,有人搜索“Hello World”一词。我的搜索结果将返回包含“hello”和“world”的所有行。
我想要实现的是:
- 突出显示搜索查询中的单词,但仅突出显示结果的一部分。我只想返回 200 个字符并突出显示(粗体)搜索词中任何单词的第一次出现。
- 显示的副本将在 CMS 中创建并具有 html 标记。我可以在显示之前去除 html 标签,但如果我以正确的方式进行操作,我希望获得反馈。
我目前使用的代码是:
// The query string:
<?php $q = urldecode($_GET['qString']); ?>
// Run a loop through the results:
<?php foreach ($this->get("pageResults") AS $result): ?>
// a clickable H3 to the actual page:
<h3><?= $this->html->link($result['sub_heading'] . " " . $result['heading'], array("controller" => "pages", "action" => "viewer", "properties" => array($result['name']))) ?></h3>
<?php
// Strip all html characters as the content comes from an WYSIWYG editor:
$value = preg_replace('/<[^>]*>/', '', $result['content']);
// Find the position within the text:
$position = stripos($value, $q);
// If a positive position, display 200 characters and start -100 from the first occurance
if ($position == true) {
$string = substr($value, $position - 100, 200);
} else {
$string = " ... ";
?>
<p><?= $string ?></p>
<hr />
<?php endforeach; ?>
我在这里遇到的主要问题是:
- 即使查询字符串,搜索结果也会返回行
不精确(因此如果该列包含
"hello" 和 "world" 而
stripos只会找到 "hello world"。 - 我不知道将
<strong></strong>标签包裹在剥离的html 中第一次出现的单词或短语周围的最佳方式。我知道这可能是一件棘手的事情,尤其是由于发生问题。没有这个功能我也可以活下去,但如果有一种很好的方法,那就太好了:)
任何想法将不胜感激!
【问题讨论】: