使用正则表达式匹配未嵌套在锚标记中的图像标记 [英] Match image tag not nested in an anchor tag using regular expression

查看:46
本文介绍了使用正则表达式匹配未嵌套在锚标记中的图像标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用正则表达式匹配未嵌套在锚标记内的图像?

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

这是我想要的:

不匹配: <a href="index.html"><img src="images/default.jpg"/></a>

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

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

我不擅长正则表达式,但这是我目前想到的,但不起作用:

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

[^]

我无法使用环视,因为 PHP 希望它是具体的.

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

推荐答案

您遇到困难的大部分原因很简单,HTML 不是常规语言,请参阅:编码恐怖:以克苏鲁方式解析 Html

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

考虑使用足够强大的查询表达式语言来处理 (X)HTML,或者仅以编程方式使用 DOM 来获取所有图像标签,然后排除那些具有 祖先的标签.

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.

在 PHP5 中,我相信你可以使用 DOMXPath,使用它变得如此简单:

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";
}

此代码将给出输出:

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

这篇关于使用正则表达式匹配未嵌套在锚标记中的图像标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆