Using regular expressions to extract the first image source from html codes?

后端 未结 10 1060
深忆病人
深忆病人 2020-12-05 01:07

I would like to know how this can be achieved.

Assume: That there\'s a lot of html code containing tables, divs, images, etc.

Problem: How can I get matches

相关标签:
10条回答
  • 2020-12-05 01:16

    You can try this:

    preg_match_all("/<img\s+src=\"(.+)\"/i", $html, $matches);
    foreach ($matches as $key=>$value) {
        echo $key . ", " . $value . "<br>";
    }
    
    0 讨论(0)
  • 2020-12-05 01:17

    Use this, is more effective:

    preg_match_all('/<img [^>]*src=["|\']([^"|\']+)/i', $html, $matches);
    foreach ($matches[1] as $key=>$value) {
        echo $value."<br>";
    }
    

    Example:

    $html = '
    <ul>     
      <li><a target="_new" href="http://www.manfromuranus.com">Man from Uranus</a></li>       
      <li><a target="_new" href="http://www.thevichygovernment.com/">The Vichy Government</a></li>      
      <li><a target="_new" href="http://www.cambridgepoetry.org/">Cambridge Poetry</a></li>      
      <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value1.jpg" />
      <li><a href="http://www.verot.net/pretty/">Electronaut Records</a></li>      
      <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value2.jpg" />
      <li><a target="_new" href="http://www.catseye-crew.com">Catseye Productions</a></li>     
      <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value3.jpg" />
    </ul>
    <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="res/upload.jpg" />
      <li><a target="_new" href="http://www.manfromuranus.com">Man from Uranus</a></li>       
      <li><a target="_new" href="http://www.thevichygovernment.com/">The Vichy Government</a></li>      
      <li><a target="_new" href="http://www.cambridgepoetry.org/">Cambridge Poetry</a></li>      
      <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value4.jpg" />
      <li><a href="http://www.verot.net/pretty/">Electronaut Records</a></li>      
      <img src="value5.jpg" />
      <li><a target="_new" href="http://www.catseye-crew.com">Catseye Productions</a></li>     
      <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value6.jpg" />
    ';   
    preg_match_all('/<img .*src=["|\']([^"|\']+)/i', $html, $matches);
    foreach ($matches[1] as $key=>$value) {
        echo $value."<br>";
    } 
    

    Output:

    value1.jpg
    value2.jpg
    value3.jpg
    res/upload.jpg
    value4.jpg
    value5.jpg
    value6.jpg
    
    0 讨论(0)
  • 2020-12-05 01:22

    While regular expressions can be good for a large variety of tasks, I find it usually falls short when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately (and by accurately I mean 100% success rate with no false positive) extract a tag.

    What I recommend you do is use a DOM parser such as SimpleHTML and use it as such:

    function get_first_image($html) {
        require_once('SimpleHTML.class.php')
    
        $post_html = str_get_html($html);
    
        $first_img = $post_html->find('img', 0);
    
        if($first_img !== null) {
            return $first_img->src;
        }
    
        return null;
    }
    

    Some may think this is overkill, but in the end, it will be easier to maintain and also allows for more extensibility. For example, using the DOM parser, I can also get the alt attribute.

    A regular expression could be devised to achieve the same goal but would be limited in such way that it would force the alt attribute to be after the src or the opposite, and to overcome this limitation would add more complexity to the regular expression.

    Also, consider the following. To properly match an <img> tag using regular expressions and to get only the src attribute (captured in group 2), you need the following regular expression:

    <\s*?img\s+[^>]*?\s*src\s*=\s*(["'])((\\?+.)*?)\1[^>]*?>
    

    And then again, the above can fail if:

    • The attribute or tag name is in capital and the i modifier is not used.
    • Quotes are not used around the src attribute.
    • Another attribute then src uses the > character somewhere in their value.
    • Some other reason I have not foreseen.

    So again, simply don't use regular expressions to parse a dom document.


    EDIT: If you want all the images:

    function get_images($html){
        require_once('SimpleHTML.class.php')
    
        $post_dom = str_get_dom($html);
    
        $img_tags = $post_dom->find('img');
    
        $images = array();
    
        foreach($img_tags as $image) {
            $images[] = $image->src;
        }
    
        return $images;
    }
    
    0 讨论(0)
  • 2020-12-05 01:27

    I don't know if you MUST use regex to get your results. If not, you could try out simpleXML and XPath, which would be much more reliable for your goal:

    First, import the HTML into a DOM Document Object. If you get errors, turn errors off for this part and be sure to turn them back on afterward:

     $dom = new DOMDocument();
     $dom -> loadHTMLFile("filename.html");
    

    Next, import the DOM into a simpleXML object, like so:

     $xml = simplexml_import_dom($dom);
    

    Now you can use a few methods to get all of your image elements (and their attributes) into an array. XPath is the one I prefer, because I've had better luck with traversing the DOM with it:

     $images = $xml -> xpath('//img/@src');
    

    This variable now can treated like an array of your image URLs:

     foreach($images as $image) {
        echo '<img src="$image" /><br />
        ';
      }
    

    Presto, all of your images, none of the fat.

    Here's the non-annotated version of the above:


     $dom = new DOMDocument();
     $dom -> loadHTMLFile("filename.html");
    
     $xml = simplexml_import_dom($dom);
    
     $images = $xml -> xpath('//img/@src');
    
     foreach($images as $image) {
        echo '<img src="$image" /><br />
        ';
      }
    
    0 讨论(0)
  • 2020-12-05 01:32

    This works for me:

    preg_match('@<img.+src="(.*)".*>@Uims', $html, $matches);
    $src = $matches[1];
    
    0 讨论(0)
  • 2020-12-05 01:32

    i assume all your src= have " around the url

    <img[^>]+src=\"([^\"]+)\"
    

    the other answers posted here make other assumsions about your code

    0 讨论(0)
提交回复
热议问题