duanmu5641 2013-04-23 18:46
浏览 125
已采纳

正则表达式找到target =“_ blank”链接并在关闭</a>标记之前添加文本

I need to be able to parse some text and find all the instances where an tag has target="_blank".... and for each match, add (for example): This link opens in a new window before the closeing tag.

For example:

Before:

<a href="http://any-website-on-the-internet-or-local-path" target="_blank">Go here now</a>

After:

<a href="http://any-website-on-the-internet-or-local-path" target="_blank">Go here now<span>(This link opens in a new window)</span></a>

This is for a PHP site, so i assume preg_replace() will be the method... i just dont have the skills to write the regex properly.

Thanks in advance for any help anyone can offer.

  • 写回答

5条回答 默认 最新

  • doudouchan5830 2013-04-23 20:08
    关注

    This does the job:

    $newText = '<span>(This link opens in a new window)</span>';
    $pattern = '~<a\s[^>]*?\btarget\s*=(?:\s*([\'"])_blank\1|_blank\b)[^>]*>[^<]*(?:<(?!/a>)[^<]*)*\K~i';
    echo preg_replace($pattern, $newText, $html);
    

    However this direct string approach may replace also commented html parts, strings or comments in css or javascript code and eventually inside javascript literal regexes, that is at best unneeded and at worst unwanted at all. That's why you should use a DOM approach if you want to avoid these pitfalls. All you have to do is to append a new node to each link with the desired attribute:

    $dom = new DOMDocument;
    libxml_use_internal_errors(true);
    $dom->loadHTML($html);
    $xp = new DOMXPath($dom);
    $nodeList = $xp->query('//a[@target="_blank"]');
    
    foreach($nodeList as $node) {
        $newNode = dom->createElement('span', '(This link opens in a new window)');
        $node->appendChild($newNode);
    }
    
    $html = $dom->saveHTML();
    

    To finish, a last alternative consists to not change the html at all and to play with css:

    a[target="_blank"]::after {
        content: " (This link opens in a new window)";
        font-style: italic;
        color: red;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?