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

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况