How to Detect a URL in a String and Convert it to a Clickable Link

This function takes a string of text as a parameter and converts any urls beginning with http:// or www. into a clickable link.

The way the function works is to split the string on whitespace and then test each segment to see if it is the beginning of a URL. Once we find and convert the links in the text, we stick each segment back together again to recreate the string.

<?php
function autolink($string)
{
$content_array = explode(" ", $string);
$output = '';

foreach($content_array as $content)
{
//starts with http://
if(substr($content, 0, 7) == "http://")
$content = '<a href="' . $content . '">' . $content . '</a>';

//starts with www.
if(substr($content, 0, 4) == "www.")
$content = '<a href="http://' . $content . '">' . $content . '</a>';

$output .= " " . $content;
}

$output = trim($output);
return $output;
}
?>

I decided to shy away from the other regex type examples I’ve seen while surfing around because it’s sometimes hard to understand and change other people’s regex, plus this way others can easily add their own additional URL checks to the function

Comments (3)
+ –

thanks for the function.
now my page looks perfect!

by noname from noname at: 5:40pm 24th May 2009

Glad to help! :D

by sean from nostin.com at: 5:12am 26th May 2009

thank you!

by kenny from hong kong at: 10:57am 11th Nov 2009