wp_targeted_link_rel()WP 5.1.0

Deprecated since 6.7.0. It is no longer supported and may be removed in future releases. It is recommended to replace this function with the same one.

Adds rel noopener to all <a target="..."> tags with the target attribute in the provided text.

Works super fast if there are no links at all — <a> tag in the text.

1 time — 0.000249 sec (fast) | 50000 times — 0.22 sec (very fast) | PHP 7.2.16, WP 5.2

No Hooks.

Returns

String. Transformed string.

Usage

wp_targeted_link_rel( $text );
$text(string) (required)
Text that contains HTML A elements.

Examples

0

#1 Demo

$text = 'Foo <a href="http://google.com" target="_blank">google</a> bar';

echo wp_targeted_link_rel( $text );
// Foo <a href="http://google.com" target="_blank" rel="noopener">google</a> bar

Since WP 5.1.0, we can add rel attributes to any bit of HTML code.
Example used in wp-includes/widgets/class-wp-widget-text.php:

$text = wp_targeted_link_rel( $text );

Changelog

Since 5.1.0 Introduced.
Since 5.6.0 Removed 'noreferrer' relationship.
Deprecated since 6.7.0

wp_targeted_link_rel() code WP 6.8.3

function wp_targeted_link_rel( $text ) {
	_deprecated_function( __FUNCTION__, '6.7.0' );

	// Don't run (more expensive) regex if no links with targets.
	if ( stripos( $text, 'target' ) === false || stripos( $text, '<a ' ) === false || is_serialized( $text ) ) {
		return $text;
	}

	$script_and_style_regex = '/<(script|style).*?<\/\\1>/si';

	preg_match_all( $script_and_style_regex, $text, $matches );
	$extra_parts = $matches[0];
	$html_parts  = preg_split( $script_and_style_regex, $text );

	foreach ( $html_parts as &$part ) {
		$part = preg_replace_callback( '|<a\s([^>]*target\s*=[^>]*)>|i', 'wp_targeted_link_rel_callback', $part );
	}

	$text = '';
	for ( $i = 0; $i < count( $html_parts ); $i++ ) {
		$text .= $html_parts[ $i ];
		if ( isset( $extra_parts[ $i ] ) ) {
			$text .= $extra_parts[ $i ];
		}
	}

	return $text;
}