Skip to content

Commit 75403cb

Browse files
committed
HTML API: Reliably parse HTML in get_url_in_content()
Trac ticket: Core-63694 This also decodes the URL whereas the previous code didn’t, so strings like `http://` will be properly decoded as `http://`.
1 parent 9bc4e2f commit 75403cb

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/wp-includes/formatting.php

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5977,17 +5977,22 @@ function wp_unslash( $value ) {
59775977
* Extracts and returns the first URL from passed content.
59785978
*
59795979
* @since 3.6.0
5980+
* @since {WP_VERSION} Reliably parses HTML via the HTML API.
59805981
*
5981-
* @param string $content A string which might contain a URL.
5982-
* @return string|false The found URL.
5982+
* @param string $content A string which might contain an `A` element with a non-empty `href` attribute.
5983+
* @return string|false Database-escaped URL via {@see esc_url} if found, otherwise `false`.
59835984
*/
59845985
function get_url_in_content( $content ) {
59855986
if ( empty( $content ) ) {
59865987
return false;
59875988
}
59885989

5989-
if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
5990-
return sanitize_url( $matches[2] );
5990+
$processor = new WP_HTML_Tag_Processor( $content );
5991+
while ( $processor->next_tag( 'A' ) ) {
5992+
$href = $processor->get_attribute( 'href' );
5993+
if ( is_string( $href ) && ! empty( $href ) ) {
5994+
return sanitize_url( $href );
5995+
}
59915996
}
59925997

59935998
return false;

0 commit comments

Comments
 (0)