PHP正则表达式。如何删除所有元素锚标记但保留具有某些href属性的锚标记包含JPG | PNG | GIF

时间:2013-06-29 16:18:04

标签: php regex href

输入

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

感谢帮助

2 个答案:

答案 0 :(得分:1)

我不是PHP开发人员,但我可以给你一个javascript演示,希望它可以给你一些帮助:)

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

答案 1 :(得分:0)

描述

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

<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

enter image description here

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>