Match image tag not nested in an anchor tag using regular expression

最后都变了- 提交于 2019-12-11 17:44:21

问题


How would I match images that is not nested inside an anchor tag using regular expression?

Here is what I want:

No match: <a href="index.html"><img src="images/default.jpg" /></a>

Match: <div><img src="images/default.jpg" /></div>

Match: <img src="images/default.jpg" />

I'm no good at regex but this is what I came up so far, which doesn't work:

[^<a[^>]*>]<img.*?/>[^</a>]

I couldn't use lookarounds since PHP wants it to be specific.


回答1:


Much of the reason behind your difficulty is simply that HTML is not a regular language, see: Coding Horror: Parsing Html the Cthulhu Way

Consider using a query expression language powerful enough to process (X)HTML, or just using the DOM programmatically to fetch all image tags and then exclude those with <a> ancestors.

In PHP5, I believe you can use DOMXPath, using that it becomes as simple as:

$generated_string = '<a href="index.html"><img src="images/inside_a.jpg" /></a>' .
                    '<div><img src="images/inside_div.jpg" /></div>' .
                    '<img src="images/inside_nothing.jpg" />';

$doc = new DOMDocument();
$doc->loadHTML($generated_string);
$xpath = new DOMXpath($doc);

$elements = $xpath->query("//*[not(self::a)]/img");

foreach ($elements as $element){
  echo $doc->saveXML($element) . "\n";
}

This code would give the output:

<img src="images/inside_div.jpg"/>
<img src="images/inside_nothing.jpg"/>



回答2:


<img[^>]*>(?![^<]*</a>)



来源:https://stackoverflow.com/questions/13244249/match-image-tag-not-nested-in-an-anchor-tag-using-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!