Many a times we need to convert a url which is in http://tech.QueryHome.com
to http://tech.QueryHome.com which requires the string to be converted in the following form <a href="http://tech.QueryHome.com">http://tech.QueryHome.com</a>
.
Following are the steps to convert it without much effort -
Step 1: Suppose you are given a string called str which contains one or more URLs.
Step 2: Run the following command to convert URLs within the str to convert all URLs to hyperlink.
$newstr = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" >$1</a>', $str);
Step 3: If you need that your link should open into a new window/tab then
$newstr = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $s);
Above steps covers only if your string is starting from http/ftp/scp what if the string is starting with www then
Step 2: Run the following command to convert URLs within the str to convert all URLs to hyperlink.
preg_replace('$(www\.[a-z0-9_./?=&-]+)(?![^<>]*>)$i', '<a href="http://$1">$1</a> ', $str);
Step 3: If you need that your link should open into a new window/tab then
preg_replace('$(www\.[a-z0-9_./?=&-]+)(?![^<>]*>)$i', '<a href="http://$1" target="_blank">$1</a> ', $str);
Now there may be occasions when you want to add the rel=nofollow attribute to your links to indicate to the search engines that you don't "trust" the link. You can simply add rel="nofollow" to the second argument.