2016-02-29 44 views
0

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轉換www。 HTTPS/HTTP到<a tag in text PHP

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

So www.google.com and http://google.com become '「但問題<img src="http://mysite/image.jpg">也成爲

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

我的PHP preg_replace代碼:

$find=array('`((?:https?|ftp)://\S+[[:alnum:]]/?)`si','`((?<!//)(www\.\S+[[:alnum:]]/?))`si', '`((?<!//)([a-z0-9_\-\+][email protected][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); 

我試圖添加URL鏈接前空間,它會轉換,但它造成的當我在第一個文本上加上鍊接時出現問題。我如何能夠感謝這一點。

回答

0

你可以在你的正則表達式的開頭添加(^|\s)來指定它是字符串的開頭還是空格。

因此,它只會查找位於字符串開頭的鏈接,或者之前有空格替換它們與您的標籤。