【问题标题】:PHP Regex. How to remove all element anchor tags but keep anchor tags with certain href attribute contain JPG|PNG|GIF [closed]PHP 正则表达式。如何删除所有元素锚标记但保留具有某些 href 属性的锚标记包含 JPG|PNG|GIF [关闭]
【发布时间】:2013-06-27 06:16:31
【问题描述】:

输入

<a href="http://mysite.com">My Site</a>
<a href="http://mysite.com/image.jpg"><img src="http://mysite.com/image.jpg"/></a>
    <a href="http://mysite.com/image.gif"><img src="http://mysite.com/image.gif"/></a>
<a href="http://yoursite.com">Your Site</a>

输出

<a href="http://mysite.com/image.jpg"><img src="http://mysite.com/image.jpg"/></a>
<a href="http://mysite.com/image.gif"><img src="http://mysite.com/image.gif"/></a>

谢谢你的帮助

【问题讨论】:

  • @mario ,我已经尝试了很多,在这里搜索和搜索。但我没有找到我正在寻找的。​​span>

标签: php regex href


【解决方案1】:

说明

这将跳过锚标记中的所有其他属性,即使它们的值看起来像嵌套在值中的属性。

<a(?=\s|>)                  # validate this is an anchor tag
(?!                         # start look ahead ! must not contain, = must contain
  (?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?   # move through tag, skipping over quoted or non quoted values
  \shref="[^"]*(?:jpg|png|gif)"                 # find href, capture value including quotes if they exist
  )                             # end look ahead
[^>]*>.*?<\/a>                  # capture the entire to the close tag

PHP 代码示例:

示例文本

注意第二行

<a href="http://mysite.com">My Site</a>
<a wrongtag=" href='http://mysite.com/image.jpg' " href="http://mysite.com">My Site</a>
<a href="http://mysite.com/image.jpg"><img src="http://mysite.com/image.jpg"/></a>
    <a href="http://mysite.com/image.gif"><img src="http://mysite.com/image.gif"/></a>
<a href="http://yoursite.com">Your Site</a>

代码

<?php
$sourcestring="your source string";
echo preg_replace('/<a(?=\s|>)
(?!  # start look ahead ! must not contain, = must contain
(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*?  # move through tag, skipping over quoted or non quoted values
\shref="[^"]*(?:jpg|png|gif)"    # find href, capture value including quotes if they exist
)    # end look ahead
[^>]*>.*?<\/a>   # actually capture the string
/imsx','',$sourcestring);
?>

匹配项

[0] => <a href="http://mysite.com/image.jpg"><img src="http://mysite.com/image.jpg"/></a>
[1] => <a href="http://mysite.com/image.gif"><img src="http://mysite.com/image.gif"/></a>

【讨论】:

    【解决方案2】:

    我不是PHP开发者,但我可以给你一个javascript demo,希望能给你一些帮助:)

    var reg=/<a\b[^>]*?href=\"((?!jpg|gif|png).)*?"[^>]*?>.*?<\/a>/gi;
    yourstr=yourstr.replace(reg,'');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 2015-05-09
      • 2011-08-11
      相关资源
      最近更新 更多