【问题标题】:find all urls (links) in text with php使用 php 在文本中查找所有 url(链接)
【发布时间】:2011-08-29 06:02:34
【问题描述】:

我有这个代码正则表达式,它应该将各种不同的 url 转换为某些文本中的链接。

preg_replace 代码是:

$regex = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@';
$text = preg_replace($regex, '<a href="$1">$1</a>', $item);

现在它几乎适用于您可以想象的所有 URL,但我遇到的问题是逗号和 URL 中的特殊字符...

问题让我感到:

http://www.sdfsdfsdf.sd/si/391,1000,1/more.html

http://sdfsddsdf-sdfsdfds.sr/component/option,com_contact/Itemid,3/lang,si/

在stackoverflow上很有趣,这两个都可以:)

谢谢,最好的问候,

【问题讨论】:

    标签: php url text preg-replace hyperlink


    【解决方案1】:

    您必须稍微编辑一下您的正则表达式。这将完成这项工作:

    $regex = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.\,]*(\?\S+)?)?)*)@';
    

    如您所见,这里添加了一个逗号[-\w/_\.\,],仅此而已。

    享受吧!

    【讨论】:

    • 逗号的问题是,如果你有“avto.si,avtooglasnik.com,avtooglasi.com”这三个将与逗号匹配,当然有什么问题:)有什么想法吗?
    • @Luka: 不,只有最后一个会与里面的逗号匹配,其他的只会匹配为不考虑逗号的域。逗号必须位于斜杠 (/) 之后,才能根据上面的正则表达式匹配为 url 的一部分
    • 但是你从来没有以逗号开头的url,所以应该是无效的,你可以这样吗?无论如何,谢谢你的回答,最好:)
    • 好的,所以这个解决方案有几个问题.. 1. it doesn't append http:// or www before url , if url inputs google.com.. 2. if someone enters "true...it" or "true..it" , it converts it to a link..
    【解决方案2】:

    尝试使用以下函数:

    function replaceURLWithHTMLLinks(text) {
      var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
      return text.replace(exp,"<a href='$1'>$1</a>"); 
    }
    

    在这里找到它:How to replace plain URLs with links?

    【讨论】:

    • 这与所有可能的 URL 不匹配,因为您将其限制为四个模式(http、https、ftp 和文件)。
    • 是的,这与很多 URL 不匹配,例如 sdkfskd.cs 或 www.google.cz 等,等等...谢谢。
    【解决方案3】:

    您可以使用这个库https://github.com/mxkh/url-finder 在 HTML 页面或文本中简单地查找 URL。我用作曲家composer require mxkh/url-finder安装

    此库还支持从流行的视频服务(如 Youtube、Vimeo)中查找视频链接。

    我希望这对某人有帮助。

    【讨论】:

      猜你喜欢
      • 2015-01-14
      • 2011-10-08
      • 1970-01-01
      • 2019-09-27
      • 2015-02-06
      • 1970-01-01
      • 2011-10-13
      • 2014-03-17
      • 2014-11-03
      相关资源
      最近更新 更多