Skip to content

Instantly share code, notes, and snippets.

@henriqueboaventura
Last active August 29, 2015 14:09
Show Gist options
  • Save henriqueboaventura/6ec217a48579b473a8a9 to your computer and use it in GitHub Desktop.
Save henriqueboaventura/6ec217a48579b473a8a9 to your computer and use it in GitHub Desktop.
<?php
function excerpt($text, $query)
{
//words
$words = join('|', explode(' ', preg_quote($query)));
//lookahead/behind assertions ensures cut between words
$s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
preg_match_all('#(?<=['.$s.']).{1,50}(('.$words.').{1,50})+(?=['.$s.'])#uis', $text, $matches, PREG_SET_ORDER);
//delimiter between occurences
$results = array();
foreach($matches as $line) {
$results[] = htmlspecialchars($line[0], 0, 'UTF-8');
}
$result = join(' <b>(...)</b> ', $results);
//highlight
$result = preg_replace('#'.$words.'#iu', "<span class=\"azul\">\$0</span>", $result);
//
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment