正则表达式匹配所有<img>标签并提取“src”属性

问题描述 投票:0回答:3

我想用正则表达式,在html文档中找到所有

img
标签并提取
src
属性的内容。

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

<img(?<prepend>[^>]+?)src=('|")?(?<src>[^\2>]+)[\2]?(?<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`

如何解决?

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

html regex regex-group regex-negation text-extraction
3个回答
4
投票

既然您在问题下面的评论中指定,在您的情况下使用正则表达式是安全...

您不能将反向引用放入集合中。它会按字面解释字符(因此在您的情况下

\2
与索引为 28 的字符字面匹配)。请使用 脾气暴躁的贪婪令牌 来代替。

请参阅此处使用的正则表达式

<img(?<prepend>[^>]+?)src=(['"])?(?<src>(?:(?!\2)[^>])+)\2?(?<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

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

0
投票

如果您使用 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
        )

)
© www.soinside.com 2019 - 2024. All rights reserved.