dongqichang7988 2018-08-14 18:21
浏览 53
已采纳

在PHP中使用Regex删除空白标签

Is it possible to remove all the blank <a> tags in some HTML code using regex?

For example,

<a href="this-goes-somewhere.com" rel="external"></a>
<a href="go-to-that-page.html"></a>
<a href="this-should-stay.html">This Should Stay</a>
<a href="this-should-stay.html"><img src="kitten.jpg"/></a>

In this case, the regex should remove the first two links. I used <a(.*?)></a> to achieve this but it matches all four links.

Any help would be appreciated.

I thought ? was meant to stop at minimum possible number of characters.

UPDATE: The HTML will not be invalid, I am generating it myself. Using Regex will be much easier in this particular case, in my opinion.

  • 写回答

1条回答 默认 最新

  • dpspn60064 2018-08-14 18:28
    关注

    I modified your regex so that it would only match the first two links by changing .* to [^<]: https://regex101.com/r/nhu2T7/2

    This PHP code will run that regex and print out the result:

    <?php
    
    $re = '/(<a[^<]*?><\/a>)/m';
    $str = '<a href="this-goes-somewhere.com" rel="external"></a>
    <a href="go-to-that-page.html"></a>
    <a href="this-should-stay.html">This Should Stay</a>
    <a href="this-should-stay.html"><img src="kitten.jpg"/></a>';
    
    echo preg_replace($re, '', $str);
    

    Result:

    <a href="this-should-stay.html">This Should Stay</a>
    <a href="this-should-stay.html"><img src="kitten.jpg"/></a>
    

    Execute at: http://sandbox.onlinephpfunctions.com/code/dd2b986b80ac6a2c7fd173f65070dd2ce1d78d3c

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效