3

我想在没有target属性的 HTML 字符串中找到所有链接,以便可以添加它。

这是一些检测属性的代码...我可以尝试搜索输出以查找是否有目标,但是有没有更简单的方法可以检测它是否具有目标属性?

$content = '<p>This is some <a href="http://www.google.com">sample text</a> with
<a href="htttp://bing.com" target="_blank" class="test">links</a>.</p>';

preg_match_all('/<a([^>]*)href="([^"]*)"([^>]*)>([^<]*)<\/a>/', $content, $matches);

print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => <a href="http://www.google.com">sample text</a>
            [1] => <a href="htttp://bing.com" target="_blank" class="test">links</a>
        )

    [1] => Array
        (
            [0] =>  
            [1] =>  
        )

    [2] => Array
        (
            [0] => http://www.google.com
            [1] => htttp://bing.com
        )

    [3] => Array
        (
            [0] => 
            [1] =>  target="_blank" class="test"
        )

    [4] => Array
        (
            [0] => sample text
            [1] => links
        )

)
4

3 回答 3

11

解决这个问题而不是正则表达式的另一种方法是使用 php DOM 扩展,它允许您通过 DOM API 对 XML 文档进行操作。这是一个例子:

$content = '<p>This is some <a href="http://www.google.com">sample text</a> 
with <a href="htttp://bing.com" target="_blank" class="test">links</a>.</p>'; 

$doc = new DOMDocument();
$doc->loadHTML($content);
$links = $doc->getElementsByTagName('a');
foreach ($links as $item) {
    if (!$item->hasAttribute('target'))
        $item->setAttribute('target','_blank');  
}
$content=$doc->saveHTML();
echo $content;

这比使用难以维护和调试的复杂正则表达式更好。

希望能帮助到你。祝你好运!

于 2013-10-01T19:46:46.013 回答
1

当我解决类似的问题时,我分两步解决了这个问题:

  1. 搜索 HTML 文档中的所有锚点标签(就像你做的那样)

  2. 对于每个找到的锚点,我应用了一个新的正则表达式,旨在列出所有属性。

很容易发现哪些没有指定目标属性。您可以从步骤 n°2 开始的一个有用的正则表达式是

(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?

我在这里找到的

于 2013-10-01T19:44:09.410 回答
0

我不确定 php 是否支持它,但这个正则表达式需要第一个 A 元素:

 <a ((?!target)[^>])+?>

在这里找到解决方案/解释https://stackoverflow.com/a/406408/1692632

于 2013-10-01T20:00:50.283 回答