dsxd62219570 2016-02-29 19:01
浏览 29
已采纳

转换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.

  • 写回答

1条回答 默认 最新

  • douhu2370 2016-02-29 19:08
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?