wp_targeted_link_rel()WP 5.1.0

Добавляет rel noopener ко всем <a target="..."> тегам с атрибутом target в переданном тексте.

Работает супер быстро, если в тексте вообще нет ссылок — <a> тега.

Работает на основе: wp_targeted_link_rel_callback()
1 раз — 0.000249 сек (быстро) | 50000 раз — 0.22 сек (очень быстро) | PHP 7.2.16, WP 5.2

Хуков нет.

Возвращает

Строку. Преобразованную строку.

Использование

wp_targeted_link_rel( $text );
$text(строка) (обязательный)
Текст в котором есть элементы HTML A.

Примеры

0

#1 Демонстрация работы

$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

Список изменений

С версии 5.1.0 Введена.
С версии 5.6.0 Removed 'noreferrer' relationship.

Код wp_targeted_link_rel() WP 6.5.2

function wp_targeted_link_rel( $text ) {
	// 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;
}