【问题标题】:Getting image url by preg_match_all通过 preg_match_all 获取图片 url
【发布时间】:2013-07-15 16:02:21
【问题描述】:
<p class="my-image my-image-zoom">
    <div id="wrap" style="top:0px;z-index:9999;position:relative;"><a href="http://img3.mysite.com/image.jpg" class="cd-zoom" id="prozoom" rel="adjustX: 5, zoomWidth:526, zoomHeight:440, adjustY:-1" style="position: relative; display: block;">
    <img width="400" height="440" id="image" src="http://img3.mysite.com/image.jpg" style="display: block;"></a><div class="mousetrap" style="background-image: url(http://www.mysite.com/); z-index: 999; position: absolute; width: 400px; height: 440px; left: 0px; top: 0px; cursor: move;"></div></div> 
</p>

我试过了

preg_match_all('/product-image-zoom">(.*?)/s',$url,$sav);
print_r($sav);

我喜欢剪辑图像源。最终我从类名中获取所有值开始。我没有发现我的代码有效。谁能帮我获取图片来源?

【问题讨论】:

    标签: php image html-parsing preg-match-all


    【解决方案1】:

    虽然不建议使用正则表达式来解析 html,但我建议您执行以下操作:

        $dom = new DOMDocument('1.0', 'utf-8');
        @$dom->loadHTML($html);
    
        $xpath_query = "//img";
        $xpath = new DOMXPath($dom);
        $xpath_query_results = $xpath->query($xpath_query);
    
        foreach($xpath_query_results as $result)
        {
            $src = $result->getAttribute('src');
            print_r($src);
        }
    

    然后您可以针对您的正则表达式测试$src 变量:)

    【讨论】:

      【解决方案2】:

      我建议不要使用正则表达式来解析 HTML。这是一个替代解决方案:

      <?php
      
      $html= '<p class="my-image my-image-zoom">
          <div id="wrap" style="top:0px;z-index:9999;position:relative;"><a href="http://img3.mysite.com/image.jpg" class="cd-zoom" id="prozoom" rel="adjustX: 5, zoomWidth:526, zoomHeight:440, adjustY:-1" style="position: relative; display: block;">
          <img width="400" height="440" id="image" src="http://img3.mysite.com/image.jpg" style="display: block;"></a><div class="mousetrap" style="background-image: url(http://www.mysite.com/); z-index: 999; position: absolute; width: 400px; height: 440px; left: 0px; top: 0px; cursor: move;"></div></div> 
          </p>';
      
      $doc = new DOMDocument();
      @$doc->loadHTML($html);
      $xpath = new DOMXPath($doc);
      $src = $xpath->evaluate("string(//img/@src)");
      
      echo $src; //output: http://img3.mysite.com/image.jpg
      
      ?>
      

      键盘:http://codepad.org/C4oKp4LI

      希望这会有所帮助!

      【讨论】:

        【解决方案3】:

        不要使用正则表达式解析 HTML。您无法使用正则表达式可靠地解析 HTML,并且您将面临悲伤和挫败感。一旦 HTML 与您的期望发生变化,您的代码就会被破坏。请参阅http://htmlparsing.com/php,了解如何使用已经编写、测试和调试过的 PHP 模块正确解析 HTML。

        【讨论】:

        • 我接受,但我需要使用正则表达式的临时解决方案。 @安迪·莱斯特
        猜你喜欢
        • 2020-05-19
        • 2012-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-29
        • 2017-06-14
        • 2016-02-04
        • 1970-01-01
        相关资源
        最近更新 更多