如何搜索不在任何html标签中的url,然后将其转换为超链接?

Kal*_*vas 2 php regex url

所以我的问题是,在相同的内容中有 iframe、图像标签等。它们都有正则表达式匹配,可以将它们转换为正确的格式。

最后剩下的就是普通的 URL。我需要一个正则表达式,它将找到所有只是链接而不是在 iframe、img 或任何其他标签内的链接。本例中使用的标签是常规 HTML 标签,而不是 BB。

目前我得到了这个代码作为内容渲染的最后一遍。但它也会对上面完成的所有其他操作(iframe 和 img 渲染)做出反应。因此它也会交换 URL。

$output = preg_replace(array(
    '%\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))%s'
), array(
    'test'
), $output);
Run Code Online (Sandbox Code Playgroud)

我的内容看起来像这样:

# dont want these to be touched
<iframe width="640" height="360" src="http://somedomain.com/but-still-its-a-link-to-somewhere/" frameborder="0"></iframe>
<img src="http://someotherdomain.com/here-is-a-img-url.jpg" border="0" />

# and only these converted
http://google.com
http://www.google.com
https://www2.google.com<br />
www.google.com
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,链接末尾也可能有一些内容。经过一整天的尝试正则表达式的工作后,最后<br />对我来说是一场噩梦。

Ro *_* Mi 5

描述

此解决方案将匹配不在标签属性值内的 url,并将它们替换为新的内容。

正则表达式匹配您跳过的内容和您替换的内容。然后 preg_match_callback 执行一个内部函数,该函数测试捕获组 1 是否已填充(这是所需的文本),如果填充则返回更改,否则仅返回不需要的文本。

我使用了您的 url 匹配正则表达式,并进行了一些小的修改,例如将未使用的捕获组(...转换)为非捕获组(?:... )。这使得正则表达式引擎运行得更快并且更容易修改表达式。

原始表达式:<(?:[^'">=]*|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*>|((?:[\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|(?:[^[:punct:]\s]|\/)))

在此输入图像描述

例子

代码

<?php

$string = '# dont want these to be touched
<iframe width="640" height="360" src="http://somedomain.com/but-still-its-a-link-to-somewhere/" frameborder="0"></iframe>
<img src="http://someotherdomain.com/here-is-a-img-url.jpg" border="0" />

# and only these converted
http://google.com
http://www.google.com
https://www2.google.com<br />
www.google.com';


    $regex = '/<(?:[^\'">=]*|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*>|((?:[\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|(?:[^[:punct:]\s]|\/)))/ims';

    $output = preg_replace_callback(
        $regex,
        function ($matches) {
            if (array_key_exists (1, $matches)) {
                return '<a href="' . $matches[1] . '">' . $matches[1] . '<\/a>';
            }
            return $matches[0];
        },
        $string
    );
    echo $output;
Run Code Online (Sandbox Code Playgroud)

输出

# dont want these to be touched
<iframe width="640" height="360" src="http://somedomain.com/but-still-its-a-link-to-somewhere/" frameborder="0"></iframe>
<img src="http://someotherdomain.com/here-is-a-img-url.jpg" border="0" />

# and only these converted
<a href="http://google.com">http://google.com<\/a>
<a href="http://www.google.com">http://www.google.com<\/a>
<a href="https://www2.google.com">https://www2.google.com<\/a><br />
<a href="www.google.com">www.google.com<\/a>
Run Code Online (Sandbox Code Playgroud)