用超链接替换URL时仅显示域名 [英] Show only the domain name when replacing a URL with hyperlink
问题描述
我有以下功能,只需在某些文本中找到一个url并将其更改为超链接;但它也显示了整个网址。如何让该函数动态显示域名?
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);
}
推荐答案
嗯,这是因为你的正则表达式匹配整个网址。你需要打破你的整个正则表达式并组成团体。
Well, that's because your regex matches to the whole url. You need to break up your whole regex and make groups.
我正在使用这个正则表达式,在我的regex101.com测试中工作正常
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]*))?)
字符串的匹配 https://www.stackoverflow.com/question/32186805
是
1) https://www.stackoverflow.com/question/32186805
2) https://www.stackoverflow.com
3) https://
4) www.stackoverflow.com
5) /question/32186805
现在我们只在第四组中拥有域名,并且可以使用 $ 4
仅显示域名为超链接文本。
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);
}
这篇关于用超链接替换URL时仅显示域名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!