转换www。 https / http到<文本PHP中的标记

转换www。  https / http到<文本PHP中的标记

问题描述:

I'm trying to convert all urls inside text into links with <a tag, I've done that buy I faced a problem and its when I enter any tag with src it changes into <a tag also I will give u some example about what Im trying to say: Let's say I want to convert this into urls links

Visit www.google.com or http://google.com <img src="http://mysite/image.jpg">

So www.google.com and http://google.com become '' but the problem <img src="http://mysite/image.jpg"> also become

<img src="<a href="http://mysite/image.jpg"></a>">

my php preg_replace code is :

$find=array('`((?:https?|ftp)://\S+[[:alnum:]]/?)`si','`((?<!//)(www\.\S+[[:alnum:]]/?))`si', '`((?<!//)([a-z0-9_\-\+]+@[a-z0-9\-]+\.\S+[[:alnum:]]/?))`si');
$replace=array('<a href="$1" target="_blank" class="comment_textLink">$1</a>','<a href="http://$1"    target="_blank" class="comment_textLink">$1</a>' ,'<a href="mailto://$1" class="comment_textLink">$1</a>');
$string = preg_replace($find, $replace, $string);

I've tried to add space before link of url which it will convert but it caused problem when I put a link on the first of text. How can I salve this thanks.

You can add (^|\s)at the beginning of your Regex to specify that it's either a beginning of a string, or a space.

Therefore, it'll only look for links that are at the beginning of a string, or has a space before to replace them with your a tags.