Getting an Image URL From IMG tag Using php

In the majority of websites, using the image on the content and the template is important. The use of images on the website can create the look of the website more attractive. In an HTML document, an image can be displayed or loaded using img tag. Attributes in the img tag is used to load an image is src. Examples of the use of img tag is:

<img src="" width="150" height="150" />

In this example, there are three attributes that are used in the img tag namely src, width and height. Src attribute is used to specify the location of the image to be loaded, the width is used to specify the image width and height to determine the height of the image when displayed on a web browser. In this post I will share about how to get the location or the url for the src attribute in the img tag in an HTML document using php.

1. Using preg_match_all and preg_match function to get the image url
The first way is to use preg_match_all and preg_match function, you can get a manual by visiting this link preg_match_all manual and preg_match manual.
 $html="Your HTML Document Here.... <img src=\"\" />";
 foreach( $imgsrc[0] as $src_attribut){
    preg_match('/src=[\'"]([^\'"]+)[\'"]/i',$src_attribut, $src[$count]);
    echo $src[$count][1]."<br>";
$html is a variable that holds html document, The code will display all images url from img tag in html string.
The code will produce:
 Download using_preg_match_to_get_image_url.php
2. Using DOM Document() to get image url
The second way is to use PHP: DOMDocument, please you check first manual of PHP: DOMDocument. Using PHP: DOMDocument to get the image url in the img tag is as follows:
  $html="Your HTML Document Here.... <img src=\"\" />";
  $document=new DOMDocument();
  foreach ($img as $src){
     echo $src['src']."<br>";
The code will produce the same output with the first way, like this:
Download using_php_DOMDocument_to_get_image_url.php

3. Using phphtmlparser to get image url 
The third way is to use phphtmlparser class. phphtmlparser class are Copyright (c) 2003 Jose Solorzano. All rights reserved. phphtmlparser allows you to interact with the HTML node and get their attributes, name and value. Before using this class, you have to download it first. Download phphtmlparser. Using phphtmlparser to get the image url in img tag is as follows:
include("");//Place the at the same directory of this file
$html="Your HTML Document Here.... <img src=\"\" />";
$parser = new HtmlParser($html);
while($parser->parse()) {
    if($parser->iNodeName == 'img') {
        echo $parser->iNodeAttributes['src']."<br>";
The code will produce the same output as the previous method.
Download using_phphtmlparser_to_get_image_url.php