Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force an HTML link to be absolute?

In my website, users can put an URL in their profile.

This URL can be http://www.google.com or www.google.com or google.com.

If I just insert in my PHP code <a href="$url">$url</a>, the link is not always absolute.

How can I force the a tag to be absolute ?

like image 962
Arnaud Avatar asked Jun 17 '13 12:06

Arnaud


3 Answers

If you prefix the URL with // it will be treated as an absolute one. For example:

<a href="//google.com">Google</a>.

Keep in mind this will use the same protocol the page is being served with (e.g. if your page's URL is https://path/to/page the resulting URL will be https://google.com).

like image 124
Marco Chiappetta Avatar answered Nov 13 '22 07:11

Marco Chiappetta


I recently had to do something similar.

if (strpos($url, 'http') === false) {
    $url = 'http://' .$url;
}

Basically, if the url doesn't contain 'http' add it to the front of the string (prefix).

Or we can do this with RegEx

$http_pattern = "/^http[s]*:\/\/[\w]+/i";

if (!preg_match($http_pattern, $url, $match)){  
   $url = 'http://' .$url;
}  

Thank you to @JamesHilton for pointing out a mistake. Thank you!

like image 20
StephanieQ Avatar answered Nov 13 '22 07:11

StephanieQ


Use a protocol, preferably http://

<a href="http://www.google.com">Google</a>

Ask users to enter url in this format, or concatenate http:// if not added.

If you prefix the URL only with //, it will use the same protocol the page is being served with.

<a href="//google.com">Google</a>
like image 10
sinhayash Avatar answered Nov 13 '22 05:11

sinhayash