protected function Highlight::highlightField in Search API 8
Marks occurrences of the search keywords in a text field.
Parameters
string $text: The text of the field.
array $keys: The search keywords entered by the user.
bool $html: (optional) Whether the text can contain HTML tags or not. In the former case, text inside tags (that is, tag names and attributes) won't be highlighted.
Return value
string The given text with all occurrences of search keywords highlighted.
2 calls to Highlight::highlightField()
- Highlight::createExcerpt in src/
Plugin/ search_api/ processor/ Highlight.php - Returns snippets from a piece of text, with certain keywords highlighted.
- Highlight::highlightFields in src/
Plugin/ search_api/ processor/ Highlight.php - Retrieves highlighted field values for the given result items.
File
- src/
Plugin/ search_api/ processor/ Highlight.php, line 627
Class
- Highlight
- Adds a highlighted excerpt to results and highlights returned fields.
Namespace
Drupal\search_api\Plugin\search_api\processorCode
protected function highlightField($text, array $keys, $html = TRUE) {
if ($html) {
$texts = preg_split('#((?:</?[[:alpha:]](?:[^>"\']*|"[^"]*"|\'[^\']\')*>)+)#i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
if ($texts === FALSE) {
$args = [
'%error_num' => preg_last_error(),
];
$this
->getLogger()
->warning('A PCRE error (#%error_num) occurred during results highlighting.', $args);
return $text;
}
$textsCount = count($texts);
for ($i = 0; $i < $textsCount; $i += 2) {
$texts[$i] = $this
->highlightField($texts[$i], $keys, FALSE);
}
return implode('', $texts);
}
$keys = implode('|', array_map('preg_quote', $keys, array_fill(0, count($keys), '/')));
// If "Highlight partial matches" is disabled, we only want to highlight
// matches that are complete words. Otherwise, we want all of them.
$boundary = !$this->configuration['highlight_partial'] ? static::$boundary : '';
$regex = '/' . $boundary . '(?:' . $keys . ')' . $boundary . '/iu';
$replace = $this->configuration['prefix'] . '\\0' . $this->configuration['suffix'];
$text = preg_replace($regex, $replace, ' ' . $text . ' ');
return trim($text);
}