我有以下功能,只需在某些文本中找到一个URL并将其更改为超链接; 但它也显示了整个网址.如何使该功能动态显示域名?
// 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);
}
Run Code Online (Sandbox Code Playgroud)
好吧,那是因为你的正则表达式匹配整个网址.你需要打破整个正则表达式并组成团队.
我正在使用这个正则表达式,在我的regex101.com测试中工作正常
((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?([A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+))((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)
Run Code Online (Sandbox Code Playgroud)
字符串的匹配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
Run Code Online (Sandbox Code Playgroud)
现在我们只在第四组中拥有域,并且可以使用$4仅显示域作为超链接文本.
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);
}
Run Code Online (Sandbox Code Playgroud)