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.

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

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型