正则表达式查找所有内部不包含标记IMG的A标记


Regular expression to find all A tags which do not contain tag IMG inside it?

我有一个HTML代码:

<a href="/in-bai-viet--Choang-n20120711033726647.chn" target="_blank">In<img src="/Images/printer.png" alt="In bài viết này" />
</a>
<a target="_blank" rel="nofollow" href="http://ttvn.vn/">Thiên Lam - TTVN
</a>
<a href="/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn" title="'abc'">
abcd
</a>

我需要删除所有不包含img标签的标签。我使用的是这个正则表达式:

preg_replace('/<a(.*)[^img](.*)<'/a>/si', '', $string);

我还在正则表达式中尝试了^(?!.+<img.+)<a href='"?''?.+'"?''?>.+</a>$,如何找到所有不包含标签IMG的标签A?但失败了。

感谢

使用这个:

(<a[^<]*>.*<img[^>]*>[^<]*</a>)

并替换为空字符串。它在这里进行了测试。

我注意到这个老问题没有勾选的答案,所以我想我会提供一个可靠的解决方案。Ria的答案在结束a标签中没有转义/,因此在链接的演示中会导致错误。此外,当提供的样本被加倍(将其与自身连接)时,Ria的regex模式会失败,因为它太贪婪,会抓取多个a标签,更不用说它比我的模式慢4倍多。

模式说明(演示):

(               #Start capture group
    <a[^<]*>    #Greedily match the opening a tag, no other tags
    [^<]*       #Greedily match characters of any length before <img
    <img[^>]*>  #Greedily match the whole img tag
    [^<]*       #Greedily match characters of any length after <img
    <'/a>       #Match the closing a tag
)               #End capture group

代码(演示):

<?php
$string="<a href='"/in-bai-viet--Choang-n20120711033726647.chn'" target='"_blank'">In<img src='"/Images/printer.png'" alt='"In bài viết này'" />
</a>
<a target='"_blank'" rel='"nofollow'" href='"http://ttvn.vn/'">Thiên Lam - TTVN
</a>
<a href='"/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn'" title='"'abc''">
abcd
</a>
<a href='"/in-bai-viet--Choang-n20120711033726647.chn'" target='"_blank'">In<img src='"/Images/printer.png'" alt='"In bài viết này'" />
</a>
<a target='"_blank'" rel='"nofollow'" href='"http://ttvn.vn/'">Thiên Lam - TTVN
</a>
<a href='"/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn'" title='"'abc''">
abcd
</a>";
echo preg_replace('/(<a[^>]*>[^<]*<img[^>]*>[^<]*<'/a>)'r?'n?/si',NULL,$string);
?>

输出:

<a target="_blank" rel="nofollow" href="http://ttvn.vn/">Thiên Lam - TTVN
</a>
<a href="/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn" title="'abc'">
abcd
</a>
<a target="_blank" rel="nofollow" href="http://ttvn.vn/">Thiên Lam - TTVN
</a>
<a href="/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn" title="'abc'">
abcd
</a>

虽然这个问题在现实生活中可能已经解决了,而且/或者不再重要,但我只想结束这个松散的结局。