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
Please check my Top 10 code snippets in PHP
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!