One of the sites that I frequent daily has an interesting take on URL’s. It is both something that I have grown to love and appreciate. After the end of each link, the domain that the link refers to is clearly printed. Why is this useful? Well, comments on a site or posts on a message board are open to links from many a user; adding the domain name after the URL helps to ensure the safety of your users, and helps them know exactly what to expect. Everyone doesn’t know to look at the link in the status bar before clicking – and this just takes one extra step out of it (plus it is simple to add).

An example:

This is a test string with http://mycoolsite.com and who knows in it.

These are definitely not the correct URLs. But what if it were like this:

This is a test string with http://mycoolsite.com [yahoo.com] and who knows [google.com] in it.

This obviously helps with identifying the URL, without having to click on it or hover over it.

With that said…. let’s get down to business.

First, build the string that will have the information that contains the URL(s).

$string = 'This is a test string with <a href="http://yahoo.com/" title="test">http://coolsite.com</a> and <a href="http://google.com">who knows</a> in it.';

Next we will use preg_replace_callback. With this built-in PHP function we will use a regular expression to find a URL in our string. The regular expression looks for everything between an anchor tag but will only use the actual URL that the anchor text is linked to. We will then create a callback function that will take the matches from our string, grab the domain using parse_url, and return it back to the string.

function addDomain($matches)
{
	$thisUrl = parse_url($matches[1]);
	$output = $matches[0] . ' <span class="addHost">[' . $thisUrl['host'] . ']</span>';
	return $output;
}
$newString = preg_replace_callback('|<a .*?href="(http://.*?)/?".*?>(.*?)</a>|', "addDomain", $string);

All together we have (with a class added for styling):

$string = 'This is a test string with <a href="http://yahoo.com/" title="test">http://coolsite.com</a> and <a href="http://google.com">who knows</a> in it.';
/**
 * Returns string with domain name after any entered URL. Actual url in anchor is used to prevent basic URL spoofing
 *
 * @param array $matches - matches found in preg_replace_callback function
 * @return string - returns URL with previous entry and domain in brackets. Styled using class "addHost".
 */
function addDomain($matches)
{
	$thisUrl = parse_url($matches[1]);
	$output = $matches[0] . ' <span class="addHost">[' . $thisUrl['host'] . ']</span>';
	return $output;
}
$newString = preg_replace_callback('|<a .*?href="(http://.*?)/?".*?>(.*?)</a>|', "addDomain", $string);


No Responses Yet to “Domain after URL”  

  1. No Comments Yet

Leave a Reply