loadHTML( $content ); //Clear all errors the were generated while parsing libxml_clear_errors(); // Restore previous error queue before HTML parse libxml_use_internal_errors( $libxml_previous_state ); $dom_xpath = new \DOMXPath( $document ); $anchor_node_list = $dom_xpath->query( "//a[contains(@rel,'noreferrer')]" ); $content_updated = false; //Remove noreferrer form amazon anchor links foreach ( $anchor_node_list as $anchor_node ) { if ( $this->has_amazon_link( $anchor_node ) ) { $this->remove_noreferrer( $anchor_node ); $content_updated = true; } } return $content_updated ? $document->saveHTML() : $content; } /** * Checks if anchor node points to amazon url. * @link https://stackoverflow.com/questions/3921066/php-regex-to-match-a-list-of-words-against-a-string * * @since 1.4.5 * * @param \DOMElement $node HTML blog content to be rendered. * * @return boolean true when $node points to amazon url other wise false. */ private function has_amazon_link( $node ) { $href_value = $node->getAttribute( 'href' ); $parsed_url = parse_url( $href_value ); return $parsed_url && array_key_exists( 'host', $parsed_url ) && preg_match_all( $this->amazon_url_regex(), $parsed_url['host'], $matches ); } /** * Removes noreferrer attribute from $node. * * @since 1.4.5 * * @param \DOMElement $node Anchor link node for which noreferrer needs to removed. * */ private function remove_noreferrer( $node ) { $rel_value = $node->getAttribute( 'rel' ); $rel_value = trim( str_replace( 'noreferrer', '', $rel_value ) ); if ( $rel_value ) { $node->setAttribute( 'rel', $rel_value ); } else { $node->removeAttribute( 'rel' ); } } /** * Generates amazon url regex from list of amazon domain names. * * @since 1.4.5 * * @return string amazon url regex */ private function amazon_url_regex() { return '/(' . implode( '$|', Content_Filter::$AMAZON_DOMAINS ) . '$)/i'; } }