用于匹配所有 <img> 标记并提取 "src" 属性的正则表达式

regex for match all <img> tag and extract the "src" attribute

我想用正则表达式在 html 文档中找到所有 img 标签并提取 src 属性的内容。

这是我的正则表达式(在线查看https://regex101.com/r/EE08dw/1):

<img(?<prepend>[^>]+?)src=('|")?(?<src>[^>]+)[]?(?<append>[^>]*)>

在测试字符串上:

<img src="aaa.jpg">

输出为:

Full match    `<img src="aaa.jpg">`
Group prepend ` `
Group 2.      "
Group srs     `aaa.jpg"`
Group append  ``

但预期输出是:

Full match    `<img src="aaa.jpg">`
Group prepend ` `
Group 2.      "
Group srs     `aaa.jpg`
Group append  ``

问题出在组 src 中,该组也匹配 " 字符:

Output:   Group srs `aaa.jpg"`
Expected: Group srs `aaa.jpg`

如何解决?

旁注:正则表达式在我的上下文中是安全的

function getAllSrc(){
var arr=document.getElementsByTagName("IMG")
var srcs=[]
for(var i = 0; i<arr.length;i++){
srcs=srcs.concat(arr[i])
}
return srcs
}

由于您在问题下方的评论中指定在您的案例中使用正则表达式 安全...

您不能在集合中放置反向引用。它会从字面上解释字符(所以在你的情况下 </code> 从字面上匹配索引为 2<sub>8</sub> 的字符)。请改用 <a href="">tempered greedy token</a>。</p> <p><a href="https://regex101.com/r/EE08dw/2" rel="nofollow noreferrer">See regex in use here</a></p> <pre><code><img(?<prepend>[^>]+?)src=(['"])?(?<src>(?:(?!)[^>])+)?(?<append>[^>]*)> ^^^^^^ ^^^^^^^^^^^^^^ ^^ 1 2 3 1: Uses set - you can do an or | as well, but using a set improves performance 2: Tempered greedy token 3: Take backreference out of set

如果你使用 php ,试试这个代码:

$thehtml = '<p>lol&nbsp;</p><p><img src="data:image/png;base64,1" data-filename="LOGO80x80.png" style="width: 25%;"></p><p>hhhhh</p><p><img src="https://avatars2.githubusercontent1.com/u/12745270?s=52&amp;v=4" alt="lol" style="width: 25%;"><br></p>';


function getImgFromPost($html){
    preg_match_all('/<img[^>]+>/i',$html, $result); 
    $img = array();
    $i = 0;
    foreach( $result[0] as $img_tag)
    {
        preg_match_all('/(src)="([^"]+)"/i',$img_tag, $img[$i]);
        $i++;
    }

    $arr0 = array();
    for ($x0 = 0; $x0 < count($img); $x0++) {
        for($x1 = 0;$x1 < count($img[$x0][1]); $x1++){
            $arr0[$x0][$img[0][1][$x1]] = $img[$x0][2][$x1];
        }
    }
    return $arr0;
}

输出将是这样的:

Array
(
    [0] => Array
        (
            [src] => data:image/png;base64,1
        )

    [1] => Array
        (
            [src] => https://avatars2.githubusercontent1.com/u/12745270?s=52&amp;v=4
        )

)