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

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)