From 20d5858046ac3d8d3acc117fb3ee38269a73e8f9 Mon Sep 17 00:00:00 2001 From: Simon Asika Date: Mon, 27 Jan 2025 17:05:24 +0800 Subject: [PATCH] Supports localhost #6 --- src/Autolink.php | 4 +++- test/AutolinkTest.php | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/Autolink.php b/src/Autolink.php index 460e444..66187eb 100644 --- a/src/Autolink.php +++ b/src/Autolink.php @@ -85,16 +85,18 @@ public function __construct(array $options = [], array $schemes = []) public function convert(string $text, array $attribs = []): string { $linkNoScheme = $this->getLinkNoScheme(); + $staticDomains = '|localhost'; if ($linkNoScheme) { $schemeRegex = "[(%s)\:\/\/@]*"; + $staticDomains = ''; } else { $schemeRegex = "(%s)\:\/\/"; } $schemeRegex = sprintf($schemeRegex, $this->getSchemes(true)); - $regex = '/(([a-zA-Z]*=")*' . $schemeRegex . "[\-\p{L}\p{N}\p{M}]+\.[\p{L}\p{M}]{2,}([\/\p{L}\p{N}\p{M}\-._~:?#\[\]@!$&'()*+,;=%\">]*)?)/u"; + $regex = '/(([a-zA-Z]*=")*' . $schemeRegex . "([\-\p{L}\p{N}\p{M}]+\.[\p{L}\p{M}]{2,}$staticDomains)([\/\p{L}\p{N}\p{M}\-._~:?#\[\]@!$&'()*+,;=%\">]*)?)/u"; return preg_replace_callback( $regex, diff --git a/test/AutolinkTest.php b/test/AutolinkTest.php index fdda256..e3d0e73 100644 --- a/test/AutolinkTest.php +++ b/test/AutolinkTest.php @@ -407,6 +407,38 @@ public function testIgnoreTrailingDot(): void ); } + public function testLocalhost(): void + { + $txt = 'Link to http://localhost with some text.'; + + $html = $this->instance->convert($txt); + + assertEquals( + 'Link to http://localhost with some text.', + $html, + ); + + $txt = 'Link to http://localhost.'; + + $html = $this->instance->convert($txt); + + assertEquals( + 'Link to http://localhost.', + $html, + ); + + // Localhost without scheme should be ignored. + $txt = 'Link to localhost.'; + + $this->instance->linkNoScheme(true); + $html = $this->instance->convert($txt); + + assertEquals( + 'Link to localhost.', + $html, + ); + } + /** * urlProvider *