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
Here’s a solution for plain text:
$str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
$keywords = array('co');
$wordspan = 5;
$keywordsPattern = implode('|', array_map(function($val) { return preg_quote($val, '/'); }, $keywords));
$matches = preg_split("/($keywordsPattern)/ui", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0, $n = count($matches); $i < $n; ++$i) {
if ($i % 2 == 0) {
$words = preg_split('/(\s+)/u', $matches[$i], -1, PREG_SPLIT_DELIM_CAPTURE);
if (count($words) > ($wordspan+1)*2) {
$matches[$i] = '…';
if ($i > 0) {
$matches[$i] = implode('', array_slice($words, 0, ($wordspan+1)*2)) . $matches[$i];
}
if ($i < $n-1) {
$matches[$i] .= implode('', array_slice($words, -($wordspan+1)*2));
}
}
} else {
$matches[$i] = ''.$matches[$i].'';
}
}
echo implode('', $matches);
With the current pattern "/($keywordsPattern)/ui" subwords are matched and highlighted. But you can change that if you want to:
If you want to match only whole words and not just subwords, use word boundaries \b:
"/\b($keywordsPattern)\b/ui"
If you want to match subwords but highlight the whole word, use put optional word characters \w in front and after the keywords:
"/(\w*?(?:$keywordsPattern)\w*)/ui"