【问题标题】:preg_match_all to find url in stringpreg_match_all 在字符串中查找 url
【发布时间】:2022-01-11 18:23:59
【问题描述】:

我从 XML 文件中获取了可能的数据。我只需要从数组中的字符串中输出 URL。采用像“https://d1.cloudfront.net/00722.jpg”这样的格式,没有其他标签和样式。我用 preg_match_all 尝试过,但没有得到任何结果。 我做错了什么?

public function xmlParserPICtn():string
{
    
    $valuesPICtn = $this->xml->xpath("//OBJEKT[@ID='91727']//PICTURE"); 
    $searchpattern="@SRC=(.*)width@";
    preg_match_all($searchpattern, $valuesPICtn, $valuesPICt); //Search-String
    foreach ($valuesPICt as $PICelements) 
      {
         $display .= '<li>';
         $display .= ''.$PICelements->PIC.'';
         $display .= '</li>';
            
        }
     $display .= '';

      return $display;
  }
  
  
  <?xml version="1.0" encoding="utf-8"?>
<OBJEKT ID="91727">
    
          <PICTURE ID="7">
              <ID>7</ID>
                  <PIC>&lt;IMG SRC="https://d1.cloudfront.net/00722.jpg" width="610" height="480" BORDER=0></PIC>
                 </PICTURE>
    
         <PICTURE ID="11">
              <ID>11</ID>
                  <PIC>&lt;IMG SRC="https://d1.cloudfront.net/01123.jpg" width="630" height="480" BORDER=0></PIC>
                 </PICTURE>
    
         <PICTURE ID="2">
                  <ID>2</ID>
                  <PIC>&lt;IMG SRC="https://d1.cloudfront.net/00224.jpg" width="740" height="480" BORDER=0></PIC>
                 </PICTURE>
    
         <PICTURE ID="9">
                  <ID>9</ID>
                  <PIC>&lt;IMG SRC="https://d1.cloudfront.net/00925.jpg" width="940" height="480" BORDER=0></PIC>
                 </PICTURE>
    
</OBJEKT>

【问题讨论】:

    标签: php regex


    【解决方案1】:

    试试这个正则表达式:

    (?<=SRC=")(.*?)(?=\")
    

    我只得到没有其他标签的 URL。

    你在这里找到了demo

    【讨论】:

    • 这根本无法回答问题,通过此更改,代码仍然无法正常工作。另请注意,如果您使用环视,则不需要捕获组。
    【解决方案2】:

    你应该循环在valuesPICtn中的xpath查询的结果

    然后对于循环中的每个项目,$PICelements-&gt;PIC 都有一张图片。您可以使用 preg_match 代替,并采用第 1 组的值。请注意,preg_matchpreg_match_all 的第二个参数采用一个字符串,您尝试在代码中传递 xpath 调用的返回值。

    请注意,代码中的这部分 $display .= ''; 可以省略,因为它连接了一个空字符串。

    模式SRC="([^"]+)" 是一个略微更新的版本,匹配 SRC=" 并在第 1 组中捕获除双引号之外的任何字符

    public function xmlParserPICtn():string
    {
        $valuesPICtn = $this->xml->xpath("//OBJEKT[@ID='91727']//PICTURE");
        foreach ($valuesPICtn as $PICelements)
        {
            $searchpattern='@SRC="([^"]+)"@';
            preg_match($searchpattern, $PICelements->PIC, $valuesPICt); //Search-String
            $display .= '<li>';
            $display .= $valuesPICt[1];
            $display .= '</li>';
        }
        return $display;
    }
    

    Php demo

    【讨论】:

    • 太棒了!您的解决方案工作正常。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2014-06-28
    • 1970-01-01
    相关资源
    最近更新 更多