You are here

protected function TooltipManager::replaceContent in Tooltip Taxonomy 8

Replace taxonomy terms with tooltip for html content. Avoid html markup tag and the attributes from being modified.

Parameters

string $html: The original html markup

array $pattern_map: Replace patterns.

Return value

string The new html markup with tooltip.

1 call to TooltipManager::replaceContent()
TooltipManager::addTooltip in src/Services/TooltipManager.php
Attach tooltip into a field text.

File

src/Services/TooltipManager.php, line 351

Class

TooltipManager
Tooltip filter condition manager class.

Namespace

Drupal\tooltip_taxonomy\Services

Code

protected function replaceContent(string $html, array $pattern_map) {
  $content_start = 0;
  $tag_begin = strpos($html, '<');
  $new_html = '';
  $length = strlen($html);
  while ($tag_begin !== FALSE) {
    $tag_end = strpos($html, '>', $tag_begin);
    if ($tag_end === FALSE) {

      // Invalid html markup.
      // Return the original html.
      return $html;
    }
    else {

      // The end '>' should be included in.
      $tag_end++;
    }
    if ($content_start >= $length) {

      // Reach the end of the html markup.
      break;
    }
    if ($content_start < $tag_begin) {

      // There are content before the tag.
      $content = substr($html, $content_start, $tag_begin - $content_start);

      // Replace the taxonomy term with tooltip.
      $new_html .= preg_replace($pattern_map['search'], $pattern_map['replace'], $content);
    }

    // Append the html tag markup.
    $new_html .= substr($html, $tag_begin, $tag_end - $tag_begin);
    $content_start = $tag_end;
    $tag_begin = strpos($html, '<', $tag_end);
  }
  if ($content_start < $length) {

    // There are content before the tag.
    $content = substr($html, $content_start, $length - $content_start);

    // Replace the taxonomy term with tooltip.
    $new_html .= preg_replace($pattern_map['search'], $pattern_map['replace'], $content);
  }
  return $new_html;
}