【问题标题】:php - Auto detect links and put them into <a> tag, except when they are already in an html tagphp - 自动检测链接并将它们放入 <a> 标签,除非它们已经在 html 标签中
【发布时间】:2012-02-01 19:32:36
【问题描述】:

我找到了一种自动检测链接并将它们放在&lt;a&gt; 标记中的解决方案:Regex PHP - Auto-detect YouTube, image and "regular" links

相关部分(出于兼容性原因,我不得不将函数移到 preg_replace_callback 调用之外):

function put_url_in_a($arr)
    {
    if(strpos($arr[0], 'http://') !== 0)
        {
            $arr[0] = 'http://' . $arr[0];
        }
        $url = parse_url($arr[0]);

        //links
        return sprintf('<a href="%1$s">%1$s</a>', $arr[0]);
    }

$s = preg_replace_callback('#(?:https?://\S+)|(?:www.\S+)|(?:\S+\.\S+)#', 'put_url_in_a', $s);

这很好用,除非它偶然发现标签中的 url,然后它会破坏(通过将另一个标签放入其中)。它还破坏了嵌入式媒体。

问题:我怎样才能排除 HTML 标签被这个函数处理,希望只使用正则表达式?

【问题讨论】:

标签: php html regex url


【解决方案1】:

一个选项 - 如果 URL 已经在链接中,则必须以 href=' 为前缀,因此排除带有 negative lookbehind 断言的链接:

#(?<!href\=['"])(?:https?://\S+)|(?:www.\S+)|(?:\S+\.\S+)#

编辑:-- 实际上,上面的表单不起作用,因为 URL 匹配太笼统,它会将 ... 之类的内容错误地转换为链接。使用我自己喜欢的 URL 匹配方案似乎可以正常工作:

$s = preg_replace_callback('#(?<!href\=[\'"])(https?|ftp|file)://[-A-Za-z0-9+&@\#/%()?=~_|$!:,.;]*[-A-Za-z0-9+&@\#/%()=~_|$]#', 'regexp_url_search', $s);

例如:http://codepad.viper-7.com/TukPdY

$s = "The following link should be linkified: http://www.google.com but not this one: <a href='http://www.google.com'>google</a>."`

变成:

The following link should be linkified: <a href="http://www.google.com">http://www.google.com</a> but not this one: <a href='http://www.google.com'>google</a>.

【讨论】:

    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    相关资源
    最近更新 更多