【发布时间】:2010-11-08 19:09:07
【问题描述】:
如何搜索前 500 个字符,不包括 html 标签?
下面是我目前想出的,就是搜索出现在文本中的关键字,
SELECT *
FROM root_pages
WHERE root_pages.pg_cat_id = '2'
AND root_pages.parent_id != root_pages.pg_id
AND root_pages.pg_hide != '1'
AND root_pages.pg_url != 'cms'
AND root_pages.pg_content_1 REGEXP '[[:<:]]".$search."[[:>:]]'
OR root_pages.pg_content_2 REGEXP '[[:<:]]".$search."[[:>:]]'
ORDER BY root_pages.pg_created DESC
如何在其中添加更多条件 - 前 500 个不包含 html 标记的字母?
如果能只搜索第一段的关键词就完美了——可以吗?
编辑:
感谢大家的帮助!这是我的解决方案:
# query to search for “whole word match” in SQL only, e.g. when I search for "rid", it should not match "arid", but it should match "a rid".
# you can use REGEXP and the [[:<:]] and [[:>:]] word-boundary markers:
$sql = "
SELECT *
FROM root_pages
WHERE root_pages.pg_cat_id = '2'
AND root_pages.parent_id != root_pages.pg_id
AND root_pages.pg_hide != '1'
AND root_pages.pg_url != 'cms'
AND root_pages.pg_content_1 REGEXP '[[:<:]]".$search."[[:>:]]'
OR root_pages.pg_content_2 REGEXP '[[:<:]]".$search."[[:>:]]'
ORDER BY root_pages.pg_created DESC
";
# use the instantiated db connection object from the init.php, to process the query
$items = $connection -> fetch_all($sql);
$total_item = $connection -> num_rows($sql);
if ($total_item > 0)
{
foreach($items as $item)
{
# get the content
if(empty($item['pg_content_2'])) $pg_content = strip_tags($item['pg_content_1']);
else $pg_content = strip_tags($item['pg_content_2']);
# get the first 500 letters only
$pg_content = substr($pg_content, 0, 500);
# get the matches
if (preg_match("/\b(".$search.")\b/", $pg_content))
{
$match[] = $pg_content;
}
}
$total_match = count($match);
//echo $count;
}
if($total_match > 0)
{
echo '<result message="'.$total_match.' matches found! Please wait while redirecting." search="'.$search.'"/>';
}
else
{
echo '<error elementid="input" message="Sorry no results are found."/>';
}
【问题讨论】:
-
我不能宽恕您提出的解决方案,因为在我看来它效率很低,但是我会问这个:考虑到您只是,是否需要显示在此页面上找到了多少结果重定向?为了使您的代码更高效,请考虑在找到第一个结果后“中断”循环。
-
是的,页面只会在找到结果时重定向。那么匹配的内容只会显示在新页面上。在找到第一个结果后,我如何“'打破'循环”?谢谢。
标签: php regex mysql full-text-search