wp_extract_urls()WP 3.7.0

Использует регулярное выражение, чтобы «вытащить» все ссылки (URL) из переданного текста.

Основа для: do_enclose()
1 раз — 0.000114 сек (быстро) | 50000 раз — 0.19 сек (очень быстро) | PHP 7.0.8, WP 4.6.1

Хуков нет.

Возвращает

Строку[]. URL найденные в переданной строке.

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

wp_extract_urls( $content );
$content(строка) (обязательный)
Контент из которого нужно получить ссылки (URL).

Примеры

0

#1 Пример извлечения ссылок из переданного контента

$content = 'Начало текста со ссылкой: http://wp-kama.ru/ 
Продолжение, теперь ссылка будет в html <a href="http://wp-example.com/foo">ссылка</a>. 
И еще один вариант, но теперь путь это будет ссылка на картинку: 
<img alt="" src="http://sitename.ru/image.jpg">. Ну и все, пока хватит.';

$urls = wp_extract_urls( $content );

/* $urls будет содержать такой массив:
Array
(
	[0] => http://wp-kama.ru/
	[1] => http://wp-example.com/foo
	[2] => http://sitename.ru/image.jpg
)
*/
0

#2 Не работает для URL-адресов localhost без TLD:

$content = '
<a href="http://localhost.com:8889/?p=9">hi</a> 
<a href="http://localhost:8889/?p=9">hi</a>     
';

$urls = wp_extract_urls( $content );

/* $urls будет содержать такой массив:
Array
(
	[0] => http://localhost.com:8889/?p=9
)
*/

See this ticket.

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

С версии 3.7.0 Введена.
С версии 6.0.0 Fixes support for HTML entities (Trac 30580).

Код wp_extract_urls() WP 6.5.2

function wp_extract_urls( $content ) {
	preg_match_all(
		"#([\"']?)("
			. '(?:([\w-]+:)?//?)'
			. '[^\s()<>]+'
			. '[.]'
			. '(?:'
				. '\([\w\d]+\)|'
				. '(?:'
					. "[^`!()\[\]{}:'\".,<>«»“”‘’\s]|"
					. '(?:[:]\d+)?/?'
				. ')+'
			. ')'
		. ")\\1#",
		$content,
		$post_links
	);

	$post_links = array_unique(
		array_map(
			static function ( $link ) {
				// Decode to replace valid entities, like &amp;.
				$link = html_entity_decode( $link );
				// Maintain backward compatibility by removing extraneous semi-colons (`;`).
				return str_replace( ';', '', $link );
			},
			$post_links[2]
		)
	);

	return array_values( $post_links );
}