You are here

protected function SearchApiHighlight::highlightField in Search API 7

Marks occurrences of the search keywords in a text field.

Parameters

string $text: The text of the field.

array $keys: Search keywords entered by the user.

bool $html: Whether the text can contain HTML tags or not. In the former case, text inside tags (i.e., tag names and attributes) won't be highlighted.

Return value

string The field's text with all occurrences of search keywords highlighted.

2 calls to SearchApiHighlight::highlightField()
SearchApiHighlight::createExcerpt in includes/processor_highlight.inc
Returns snippets from a piece of text, with certain keywords highlighted.
SearchApiHighlight::postprocessSearchResults in includes/processor_highlight.inc
Does nothing.

File

includes/processor_highlight.inc, line 479
Contains the SearchApiHighlight class.

Class

SearchApiHighlight
Processor for highlighting search results.

Code

protected function highlightField($text, array $keys, $html = TRUE) {
  if (is_array($text)) {
    $text = $this
      ->flattenArrayValues($text);
  }
  if ($html) {
    $texts = preg_split('#((?:</?[[:alpha:]](?:[^>"\']*|"[^"]*"|\'[^\']\')*>)+)#i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    for ($i = 0; $i < count($texts); $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 = empty($this->options['highlight_partial']) ? self::$boundary : '';
  $regex = '/' . $boundary . '(?:' . $keys . ')' . $boundary . '/iu';
  $replace = $this->options['prefix'] . '\\0' . $this->options['suffix'];
  $text = preg_replace($regex, $replace, ' ' . $text . ' ');
  return substr($text, 1, -1);
}