Convert links in a string of text to hyperlinks

Submitted by:Jhon Brain

Date added:28 April, 2012

Category:PHP

Convert a string of text and ad hyperlinks to all the URLs. We loop through each URL and add a hyperlink

Tags: text to hyperlinks

Code Snippet:

function url_to_link($text){

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the string
if (preg_match_all($reg_exUrl, $text, $url)) {

foreach($url[0] as $v){

$position = strpos($text,' '.$v)+1;
$text = substr_replace($text,'', $position, strlen($v));
$text = substr_replace($text,''.$v.'', $position ,0);
}
return $text;
}
else {
// if no urls in the text just return the text
return $text;
}
}

$string = 'This is a string of text and we have a link: http://www.xentrik.net
we also have another link http://google.com';
echo url_to_link($string);
 
 

Comments