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????
str_replace()would be enough, as long as you're dealing with plain html. Anyway, theregexexpression mentioned seems overcomplicated comparing to it's subject.