improvements-2.x-dev/src/Plugin/Filter/NofollowExternalLinksFilter.php
src/Plugin/Filter/NofollowExternalLinksFilter.php
<?php namespace Drupal\improvements\Plugin\Filter; use Drupal\Component\Utility\Html; use Drupal\Component\Utility\UrlHelper; use Drupal\filter\FilterProcessResult; use Drupal\filter\Plugin\FilterBase; /** * @Filter( * id = "nofollow_external_links_filter", * title = @Translation("Nofollow external link"), * description = @Translation("Add attribute rel=nofollow to external links."), * type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE, * weight = 20, * ) */ class NofollowExternalLinksFilter extends FilterBase { /** * {@inheritdoc} */ public function process($text, $langcode): FilterProcessResult { $result = new FilterProcessResult($text); if (stripos($text, '<a') !== FALSE) { $html_dom = Html::load($text); $links = $html_dom->getElementsByTagName('a'); foreach ($links as $link) { $link_href = $link->getAttribute('href'); if (UrlHelper::isExternal($link_href)) { $link->setAttribute('rel', 'nofollow'); } } $result->setProcessedText(Html::serialize($html_dom)); } return $result; } }