Tidying search results from database php

大城市里の小女人 提交于 2019-12-08 05:31:47

问题


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??


回答1:


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;
}


来源:https://stackoverflow.com/questions/7944451/tidying-search-results-from-database-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!