public highlight ( string $text, string $phrase, string $format = '<span class="highlight">\1</span>', boolean $html = false, string $regex = "|%s|iu" ) : mixed | ||
$text | string | Text to search the phrase in |
$phrase | string | The phrase that will be searched |
$format | string | The piece of html with that the phrase will be highlighted |
$html | boolean | If true, will ignore any HTML tags, ensuring that only the correct text is highlighted |
$regex | string | a custom regex rule that is used to match words, default is '|$tag|iu' |
return | mixed |
public function highlight($text, $phrase, $format = '<span class="highlight">\\1</span>', $html = false, $regex = "|%s|iu")
{
if (empty($phrase)) {
return $text;
}
if (is_array($phrase)) {
$replace = array();
$with = array();
foreach ($phrase as $key => $segment) {
$segment = '(' . preg_quote($segment, '|') . ')';
if ($html) {
$segment = "(?![^<]+>){$segment}(?![^<]+>)";
}
$with[] = is_array($format) ? $format[$key] : $format;
$replace[] = sprintf($regex, $segment);
}
return preg_replace($replace, $with, $text);
}
$phrase = '(' . preg_quote($phrase, '|') . ')';
if ($html) {
$phrase = "(?![^<]+>){$phrase}(?![^<]+>)";
}
return preg_replace(sprintf($regex, $phrase), $format, $text);
}