Show only the domain name when replacing a URL with hyperlink

大城市里の小女人 提交于 2020-01-06 17:56:47

问题


I have the function below to simply find a url in some text and change it to a hyperlink; but it also shows the entire url. How can I make the function show only the domain name dynamically?

// URL TO HYPERLINK
function activeUrl($string) {
$find = array('`((?:https?|ftp)://\S+[[:alnum:]]/?)`si', '`((?<!//)(www\.\S+[[:alnum:]]/?))`si');

$replace = array('<a href="$1" target="_blank">$1</a>', '<a href="http://$1" target="_blank">$1</a>');
return preg_replace($find,$replace,$string);
}

回答1:


Well, that's because your regex matches to the whole url. You need to break up your whole regex and make groups.

I am using this regex, which works fine in my test on regex101.com

((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?([A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+))((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)

The matches for the string https://www.stackoverflow.com/question/32186805 are

1) https://www.stackoverflow.com/question/32186805
2) https://www.stackoverflow.com
3) https://
4) www.stackoverflow.com
5) /question/32186805

Now we have the domain only in the fourth group and can use $4 to only show the domain as the hyperlink text.

function activeUrl($string) {
    $find = '/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?([A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+))((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/si';

    $replace = '<a href="$1" target="_blank">$4</a>';
    return preg_replace($find, $replace, $string);
}



回答2:


You can use preg_match_all to extract the url then parse_url function to take only the domain name.

function extractUrl ($string) {
    preg_match_all('!https?://\S+!', $string, $matches);
    $url = $matches[0];
    $parsedUrl = parse_url($url[0]); // Use foreach in case you have more than one url. 
    $domain="http://".$parsedUrl['host'];
    return $domain;
}

$string="this is a url http://yourUrl.com/something/anything";
echo extractUrl($string); //http://yourUrl.com


来源:https://stackoverflow.com/questions/32186805/show-only-the-domain-name-when-replacing-a-url-with-hyperlink

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!