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 用lstm来预测股票价格
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上