get_url_in_content( string $content ): string|false

In this article

Extracts and returns the first URL from passed content.

Parameters

$contentstringrequired
A string which might contain an A element with a non-empty href attribute.

Return

string|false Database-escaped URL via esc_url() if found, otherwise false.

Source

function get_url_in_content( $content ) {
	if ( empty( $content ) ) {
		return false;
	}

	$processor = new WP_HTML_Tag_Processor( $content );
	while ( $processor->next_tag( 'A' ) ) {
		$href = $processor->get_attribute( 'href' );
		if ( is_string( $href ) && '' !== $href ) {
			return sanitize_url( $href );
		}
	}

	return false;
}

Changelog

VersionDescription
3.6.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.