urls2linksSimple - Link Converting Function
Description
This is the demonstration of a php function that turns all URLs in a string into hyperlinks. It is intended for use in scripts such as forum or message board software, so URLs typed into messages can be automatically turned into hyperlinks.
string urls2linksSimple( string $urls )
It searches for all URLs in the string $urls
, with or without a protocol (e.g. 'www.bbc.co.uk' or 'http://www.google.com'), finding the entire address: protocol, host, port, path, query string and fragment. The URLs are replaced with HTML anchor tags (<a href="...">) and the result returned.
If there is a punctuation mark directly after the URL, it excludes that from the link. Punctuation marks being included in links is a common problem on message boards. The function is made to be able to take text with simple HTML tags in (such as <br/>). It may also work with tags that have URLs in, such as <img> tags, but these are not supported by design. Experiment with HTML tags in the demonstration box below. To convert line breaks to <br/> tags, use the nl2br(string) function on the text before passing it to this function. For example: urls2linksSimple(nl2br($text))
The urls2linksSimple function code and license info is shown at the bottom of the page.
See also:
The more complex urls2links function, which can recognise e-mail addresses and more complex URLs: urls2linksComplex
The php function code:
Please feel free to use this code in your own scripts, and to modify it to suit your purposes. I've made it simple - you pass it one variable and it passes one back - but you may want it to work in a different way.
If you do use this function, please leave the note with my details intact, thank you.
function urls2linksSimple($text){
//"urls2links - Simple" function by Martin Pain / m-bread ( http://m-bread.com/resources/php/functions/urls2linksSimple )
//This function can be distributed under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License
//( http://creativecommons.org/licenses/by-sa/2.0/uk/ )
//Please leave these comments intact.
$pattern = '\b(((((H|h)(T|t)|(F|f))(T|t)(P|p)((S|s)?))\://)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}';
$pattern .= '(\:[0-9]{1,5})*(/(|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+?))*)($|[^\w/][<\s]|[<\s]|[^\w/]$)';
$replacement = '\'<a href="\'.((\'$4\' == \'\')?\'http://$1\':\'$1\').\'"
>$1</a>$16\'';
return preg_replace('¦'.$pattern.'¦e', $replacement, $text);
};//EoFn urls2links
License
These urls2Links php functions are licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License by Martin Pain. This means you are free to use, distribute and modify the functions, as long as you distribute any work you use it in under a similar licence. Click on the image or licence name for more information.
You can also see the other urls2links function, urls2linksComplex,
and the rest of my projects & resources.
