I am using preg_replace to create a snippet of searched content on my site and highlight the term that was searched (like google). It works when I use a static variable on my page but when I retrieve the data from the database it doesn’t. The code is as follows:
foreach ($searchcontent ->result() as $row)
{
$text = $row->content;
$keyword = 'investment';
$size = 165;
$snippet = preg_replace(
'/^.*?\s(.{0,'.$size.'})(\b'.$keyword.'\b)(.{0,'.$size.'})\s.*?$/',
'...$1<strong>$2</strong>$3...',
$text
);
echo $snippet;
}
If I change the $text variable for some static content like:
"We are happy to consultant on your investments" it works. But when I get the data from the db it doesn’t.
Sample of text from database (contains html, may be the issue),
<h2>Investments<h2>
<hr />
<p>We are happy to consult on your investments</p>
How would one go about stripping the string of html tags?? and getting the preg_replace working????
This works : http://codepad.org/Ve1dhj8q
However, it would be better if you paste a real database result, since the problem might be there.
Edit
This is what you want. You can use
preg_match()to capture the contents before ($matches[1]) and after ($matches[2]), and don’t forget to check if there was any match found ( usingcount()). Only thing left is to add the previous posted code in order to highlight the words.$limitis the offset.Example output
Bonus
If you for design / markup purposes need to limit the phrase to, lets say 100 words (example, in case your div container can only take a certain amount of characters in order to keep the layout balance), you can do this :