Tidying search results from database php

2019-06-03 11:29发布

问题:

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