【问题标题】:regex for match all <img> tag and extract the "src" attribute正则表达式匹配所有 <img> 标记并提取“src”属性
【发布时间】:2018-01-25 19:40:56
【问题描述】:

我想用正则表达式找到所有img标签到html文档中并提取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-negation regex-group


【解决方案1】:

由于您在问题下方的 cmets 中指定在您的情况下使用正则表达式是安全...

您不能将反向引用放在集合中。它会按字面解释字符(因此在您的情况下,\2 与索引为 28 的字符相匹配)。请改用tempered greedy token

See regex in use here

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-02
        • 1970-01-01
        • 2011-10-07
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多