Show only the domain name when replacing a URL wit

2019-08-22 14:28发布

问题:

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


标签: php hyperlink