From 4015caefdc3b791e66fbfb8b80ad48a809253f72 Mon Sep 17 00:00:00 2001 From: Ankit Parmar Date: Thu, 26 Nov 2026 16:46:29 +0530 Subject: [PATCH] Formatting: Avoid nested links in `make_clickable()` when link text has surrounding content. The final cleanup in `make_clickable()` only removed an accidental link inside a link when the nested link was the sole content of the outer link. Any text around it, even whitespace, left output like ` ...`. The cleanup now keeps text before and after the nested link, limited to a single outer link so adjacent links are left untouched. See #50514. --- src/wp-includes/formatting.php | 4 +-- .../tests/formatting/makeClickable.php | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/formatting.php b/src/wp-includes/formatting.php index ad12579fdafa1..c6b15e2aa7380 100644 --- a/src/wp-includes/formatting.php +++ b/src/wp-includes/formatting.php @@ -3274,8 +3274,8 @@ function make_clickable( $text ) { } } - // Cleanup of accidental links within links. - return preg_replace( '#(]+?>|>))]+?>([^>]+?)#i', '$1$3', $r ); + // Cleanup of accidental links within links, keeping any text around the nested link. + return preg_replace( '#(]+?>|>))([^<]*)]+?>([^>]+?)([^<]*)#i', '$1$3$4$5', $r ); } /** diff --git a/tests/phpunit/tests/formatting/makeClickable.php b/tests/phpunit/tests/formatting/makeClickable.php index 09ca0d48cff68..7946ae27567c0 100644 --- a/tests/phpunit/tests/formatting/makeClickable.php +++ b/tests/phpunit/tests/formatting/makeClickable.php @@ -455,6 +455,35 @@ public function test_line_break_in_existing_clickable_link() { $this->assertSame( $html, make_clickable( $html ) ); } + /** + * Tests that a URL inside an existing link is not linked a second time. + * + * @ticket 50514 + * @dataProvider data_url_inside_existing_link + * + * @param string $html Content that already contains a link. + */ + public function test_url_inside_existing_link_is_not_nested( $html ) { + $this->assertSame( $html, make_clickable( $html ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_url_inside_existing_link() { + return array( + 'link text is only the URL' => array( 'https://w.org' ), + 'space before the URL' => array( ' https://w.org' ), + 'space after the URL' => array( 'https://w.org ' ), + 'text before and after the URL' => array( 'Visit https://w.org now' ), + 'newline before the URL' => array( "\nhttps://w.org" ), + 'two adjacent links' => array( 'http://example.com/http://example.com/' ), + 'two links separated by text' => array( 'http://example.com/a and http://example.com/b' ), + ); + } + /** * @ticket 30162 * @dataProvider data_script_and_style_tags