【问题标题】:REGEX where img tag does not have altimg 标签没有 alt 的正则表达式
【发布时间】:2019-04-02 17:03:43
【问题描述】:

我正在尝试编写一个正则表达式来查找没有 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 的链接 https://regex101.com/r/Z5vkQb/3/

【问题讨论】:

  • 试试&lt;img\b(?![^&gt;]*? alt=)[^&gt;]*&gt;

标签: html regex image alt


【解决方案1】:

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
}

【讨论】:

    【解决方案2】:

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

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

    Demo

    【讨论】:

    • &lt;img src="whatever.png" title="should match but alt= in here makes it fail ;)" /&gt; - 使用正则表达式解析 HTML 不起作用!!!
    【解决方案3】:

    你可以使用这个表达式:

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

    【讨论】:

    • &lt;img src="salt.png" /&gt; 让你很咸,因为你的表达失败了。
    • alt 之后包含=。例如&lt;img[^&gt;]*alt=[^&gt;]*&gt;
    • &lt;img src="dynamic.php?salt=true" /&gt;
    • &lt;img[^&gt;]*\s+alt=[^&gt;]*&gt;
    • &lt;img src="whatever.png" title="Am I being annoying yet? alt=regexes do not work." /&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多