【问题标题】:Add target attribute to html links将目标属性添加到 html 链接
【发布时间】:2013-10-01 19:32:51
【问题描述】:

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

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

$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
        )

)

【问题讨论】:

  • preg_replace_callback可能是你的朋友:php.net/manual/en/function.preg-replace-callback.php首先匹配完整的锚标签&lt;a .... &gt;然后在回调中搜索目标属性。而且鲍尔默先生不会对htttp://bing.com 很满意。哦,等等……

标签: php regex


【解决方案1】:

解决此问题的另一种方法是使用 php DOM extension,而不是正则表达式,它允许您通过 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;

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

希望对您有所帮助。祝你好运!

【讨论】:

    【解决方案2】:

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

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

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

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

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

    我找到了here

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-01
        • 2015-03-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多