Fix URL-autolinking regex

This commit is contained in:
NotAlexNoyle committed 2026-06-03 17:30:13 +00:00
1 parent f365679cb9
commit f7b8fce6ff
1 file changed
+16 -27
+16 -27
View File
@@ -52,35 +52,24 @@ if (count($shareparts) > 1) {
gracefuldeath_httpcode(400); gracefuldeath_httpcode(400);
} }
function turnUrlIntoHyperlink($string){ function turnUrlIntoHyperlink($string) {
//https://stackoverflow.com/questions/23366790/php-find-all-links-in-the-text $pattern = '~\b((?:https?://|ftp://|www\.)[^\s<>"\']+)~i';
//The Regular Expression filter
$reg_exUrl = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»""'']))/";
// Check if there is a url in the text return preg_replace_callback($pattern, function ($matches) {
if(preg_match_all($reg_exUrl, $string, $url)) { $display = $matches[1];
// Loop through all matches $href = $display;
foreach($url[0] as $newLinks){
// Decode the URL since the string is already HTML-encoded if (stripos($href, 'www.') === 0) {
$decodedLink = html_entity_decode($newLinks, ENT_QUOTES, 'UTF-8'); $href = 'http://' . $href;
if(strstr($decodedLink, ":" ) === false){
$link = 'http://'.$decodedLink;
}else{
$link = $decodedLink;
}
// Validate URL scheme to prevent javascript: and data: URLs
$parsedUrl = parse_url($link);
if (isset($parsedUrl['scheme']) && !in_array(strtolower($parsedUrl['scheme']), ['http', 'https', 'ftp'])) {
continue; // Skip invalid/dangerous schemes
}
// Create Search and Replace strings with proper encoding
$search = $newLinks;
$replace = '<a href="'.safe_html_output($link).'">'.safe_html_output($decodedLink).'</a>';
$string = str_replace($search, $replace, $string);
} }
}
return $string; $parsedUrl = parse_url($href);
if (!isset($parsedUrl['scheme']) || !in_array(strtolower($parsedUrl['scheme']), ['http', 'https', 'ftp'], true)) {
return $display;
}
return '<a href="' . safe_html_output($href) . '">' . safe_html_output($display) . '</a>';
}, $string);
} }
?> ?>