正则表达式,其中 img 标签没有 alt

REGEX where img tag does not have alt

我正在尝试编写一个正则表达式来查找没有 alt 属性的 img 标签。

这是正则表达式。

<img\s+src.+^(?!alt).+$

这里有一些示例

<img src="smiley.gif" alt="Smiley face" height="42" width="42">
<img src="smiley2.gif" height="42" width="42">
<img src="smiley3.gif" alt="Smiley face Three" height="42" width="42">

这是 regex101 的 link https://regex101.com/r/Z5vkQb/3/

您可以使用这个表达式:

<img[^>]*alt=[^>]*>

如果在同一行内,可以使用这个,

<img(?!.*\s+alt\s*=).+$

Demo

Don't.

您没有指定您使用的是哪种语言,但很可能您有 DOM 可用的解析器。

例如,在JavaScript中,您可以这样做:

var imgs_with_no_alt = document.querySelectorAll("img:not([alt])");

在 PHP 中你需要这样的东西:

$dom = new DOMDocument();
$dom->loadHTML("your HTML here");
$images = $dom->getElementsByTagName("img");
foreach($images as $image) {
    if( $image->getAttribute("alt")) continue;
    // do something to $image here, which doesn't have an [alt] attribute
}