preg_replace – Searches $subject for matches to $pattern and replaces them with $replacement.

By using the above preg_replace function I have created a simple function which will first find urls inside text and convert all into clickable links

PHP Code :


function convert_links($text)
{
 $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\1:", $text);
 $ret = ' ' . $text;
 $ret = preg_replace("#(^|[n ])([w]+?://[w#$%&~/.-;:=,?@[]+]*)#is", "\1<a href="\2" target="_blank">\2</a>", $ret);
 $ret = preg_replace("#(^|[n ])((www|ftp).[w#$%&~/.-;:=,?@[]+]*)#is", "\1<a href="http://\2" target="_blank">\2</a>", $ret);
 $ret = preg_replace("#(^|[n ])([a-z0-9&-_.]+?)@([w-]+.([w-.]+.)*[w]+)#i", "\1<a href="mailto:\2@\3">\2@\3</a>", $ret);
 $ret = substr($ret, 1);
 preg_match_all("/<a href="(.+?)"/", $ret, $match);
 $result1 = array_unique($match);
 $count = count($result1[0]);
 if($count > 0)
 {
 foreach ($result1 as $val)
 {
 foreach ($val as $item)
 {
 $item = str_replace('<a href="', '', $item);
 $item = str_replace('"', '', $item);
 }
 }
 }
 return $ret;
}

Usage


echo convert_links('your text here');

Please don’t forget to share and subscribe to latest updates of the blog. 

Thanks!

If you enjoyed this article, Get email updates (It’s Free)
http://w3lessons.info/wp-content/uploads/2011/12/IMG_29591-1024x711.jpghttp://w3lessons.info/wp-content/uploads/2011/12/IMG_29591-150x150.jpgKarthikeyan KPHPnew techniques,php
preg_replace - Searches $subject for matches to $pattern and replaces them with $replacement.By using the above preg_replace function I have created a simple function which will first find urls inside text and convert all into clickable links PHP Code :UsagePlease don’t forget to share and subscribe to latest updates of the...