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)
+ –