I need to highlight a keyword in a paragraph, as google does in its search results. Let\'s assume that I have a MySQL db with blog posts. When a user searches for a certain
If you wish to cut out the relevant paragraphs, after doing the above mentions str_replace function, you can use stripos() to find the position of these strong sections, and use an offset of that location with substr() to cut out a section of the paragraph, such as:
$searchterms;
foreach($searchterms as $search)
{
$paragraph = str_replace($search, "$search", $paragraph);
}
$pos = 0;
for($i = 0; $i < 4; $i++)
{
$pos = stripos($paragraph, "", $pos);
$section[$i] = substr($paragraph, $pos - 100, 200);
}
which will give you an array of small sentences (200 characters each) to use how you wish. It may also be beneficial to search for the nearest space from the cutting locations, and cut from there to prevent half-words. Oh, and you also need to check for errors, but I'll leave that but up to you.