整理来自数据库php的搜索结果 [英] Tidying search results from database php

查看:74
本文介绍了整理来自数据库php的搜索结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的用户在我的网站上搜索内容时,我会回声$title, $content,就像$keyword

实现的搜索功能可以正常工作,但是,由于数据库中的每个内容字段都包含相当多的文本段落,因此当页面上显示结果时,用户将很难阅读.

我希望用户搜索输入的关键字,然后在显示的结果中,将关键字前后的文本切成若干字母并突出显示?

我已经读过strpos和strstr应该这样做.所以我的问题是...

使用以下代码:

<?php 

foreach ($searchcontent ->result() as $row)
{
echo $title
echo $content
}
?>

如何突出显示该关键字,并在找到的第一个关键字的两侧显示多个字符??

解决方案

您可以执行以下操作:

在PHP脚本中

$keyword = THESEARCHEDKEYWORD;
$pattern = "/([^a-z])$keyword([^a-z])/i";
$highlight = '<span class="highlight">' . $keyword . '</span>';
foreach ($searchcontent->result() as $row)
{
   $title = preg_replace($pattern, "$1$highlight$2", $title);
   $content = preg_replace($pattern, "$1$highlight$2", $content);
   echo $title;
   echo $content;
}

然后在CSS中添加此规则 :

.highlight
{
   font-weight: bold;
   background-color: yellow;
}

When my users search for content on my website I echo $title, $content where like $keyword

The search function implemented works correctly but, because each content field in my database contains quite a few paragraphs of text it makes it hard for users to read when the results are displayed on the page.

I would like the user to search for the keyword entered and then in the results displayed, chop the text some number of letters before and after the keyword and highlight it?

I have read that strpos and strstr should do it. So my question is....

With the following code:

<?php 

foreach ($searchcontent ->result() as $row)
{
echo $title
echo $content
}
?>

How can I highlight the keyword and display a number of characters on each side of the first keyword found??

解决方案

You can do something like this:

In the PHP script

$keyword = THESEARCHEDKEYWORD;
$pattern = "/([^a-z])$keyword([^a-z])/i";
$highlight = '<span class="highlight">' . $keyword . '</span>';
foreach ($searchcontent->result() as $row)
{
   $title = preg_replace($pattern, "$1$highlight$2", $title);
   $content = preg_replace($pattern, "$1$highlight$2", $content);
   echo $title;
   echo $content;
}

And then add this rule in the CSS:

.highlight
{
   font-weight: bold;
   background-color: yellow;
}

这篇关于整理来自数据库php的搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆