I'm not sure if this can be done simply. I have made a forum in which users can insert links in their posts. If someone writes www.google.com (within asterisks ) , then i am simply using php to change it to

<a href='www.google.com' target='_blank' >www.google.com</a>

The problem is that if my site is http://www.mysite.com , then on clicking the above link, the page http://www.mysite.com/www.google.com opens, which does not exist. When a user enters the complete url with the protocol, i.e., http://www.google.com, then the link works fine. However , I cannot really expect everyuser to enter a complete URL. How can I make the link work with such URL's as www.google.com ?

2 answers

Doug 1095

You will probably have to use regex to match the URL and use PHP to prepend the "http://" onto URLs that don't have it. How are you even detecting the URLs in the first place? Research into how other forum software programs solve this problem.

Answered over 8 years ago by Doug

Whenever a user inputs a value, check the url for the http:// prefix, if its not there, add it. This should be done with PHP. And then probably regex is the way to go (but regex can be a pain in the ass ;p), you could also just use substr to check the first couple of characters in the string and then just use a switch or if..else statement to prefix with http:// (or not).

Also, you could use jquery to let all the external links open in a new window (Tutorial), check the comments for variations. This means you don't have to put target="_blank" on every anchor. Also this gives you the possibillity to add a class to every external anchor, so you can add an image or whatever to external links.

Answered over 8 years ago by Menno Geelen