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.
I am using this regex, which works fine in my test on regex101.com
The matches for the string
https://www.stackoverflow.com/question/32186805
areNow we have the domain only in the fourth group and can use
$4
to only show the domain as the hyperlink text.You can use
preg_match_all
to extract the url thenparse_url
function to take only the domain name.