doy51723 2015-05-26 11:58
浏览 24
已采纳

preg_replace与超链接有关

before I decided to post my first question on StackOverflow I turned completely crazy, so here it goes:

I've got a website that uses Google Calendar API to fetch event entries. In the description section users can fill in some details about the event. Now i'd like them to be able to put in hyperlinks. This can happen in a couple of ways. User types:

  • www.test.com
  • http(s)://test.com
  • http(s)://www.test.com
  • <a href="[one of above]" target="_blank">test.com</a>

What I'm desperately looking for is a way to convert them all to the format <a href="[http:// OR https:// OR www.]test.com" target="_blank">test.com</a>

I have already tried this syntax:

$pattern = "/(?i)\b((!<?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
$description = preg_replace($pattern, "<a href='http://$1'>$1</a>", $description);

It does change all events in the format www.test.com in a correct hyperlink, it does not change events in the format http(s)://www.test.com and http(s)://test.com. Input in the format <a href="[one of above]" target="_blank">test.com</a> becomes a mess.

Now I'm sad and tired. If someone could help me out, you're an absolute genius!

  • 写回答

3条回答 默认 最新

  • doujing6436 2015-05-27 08:47
    关注

    Finally solved it with a condition in PHP: here's the code so others can use it as well. Does add the path after .domain/ now.
    Thanks a lot for your help!

    if (!stristr($description, '<a href')){
      $pattern = "~(?:https?://)?((?:[\\p{L}\\p{N}-]+\\.)+[\\p{L}-]{2,5})((\\S)*)~m";
      $description = preg_replace($pattern, "<a href=\"$0\" target=\"_blank\">$0</a>", $description);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里