Fix URL-autolinking regex
This commit is contained in:
1 parent
f365679cb9
commit
f7b8fce6ff
1 file changed
+16
-27
@@ -52,35 +52,24 @@ if (count($shareparts) > 1) {
|
||||
gracefuldeath_httpcode(400);
|
||||
}
|
||||
|
||||
function turnUrlIntoHyperlink($string){
|
||||
//https://stackoverflow.com/questions/23366790/php-find-all-links-in-the-text
|
||||
//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`!()\[\]{};:'\".,<>?«»""'']))/";
|
||||
function turnUrlIntoHyperlink($string) {
|
||||
$pattern = '~\b((?:https?://|ftp://|www\.)[^\s<>"\']+)~i';
|
||||
|
||||
// Check if there is a url in the text
|
||||
if(preg_match_all($reg_exUrl, $string, $url)) {
|
||||
// Loop through all matches
|
||||
foreach($url[0] as $newLinks){
|
||||
// Decode the URL since the string is already HTML-encoded
|
||||
$decodedLink = html_entity_decode($newLinks, ENT_QUOTES, 'UTF-8');
|
||||
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 preg_replace_callback($pattern, function ($matches) {
|
||||
$display = $matches[1];
|
||||
$href = $display;
|
||||
|
||||
if (stripos($href, 'www.') === 0) {
|
||||
$href = 'http://' . $href;
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
?>
|
||||
Reference in new issue
Block a user