Last active
August 29, 2015 14:09
-
-
Save henriqueboaventura/6ec217a48579b473a8a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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