Get src value of the first occurring img tag in an HTML document

Get src value of the first occurring img tag in an HTML document

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting the First Image Source from an HTML String

Parsing raw HTML to extract specific attributes like src requires moving beyond simple string manipulation. When you need to pull the source URL of the first <img> tag from a massive block of text—such as the content of a news story—you are dealing with untrusted, unstructured data. The most robust approach involves using a dedicated HTML parser rather than regex or naive substring searches.

While regular expressions might seem like a quick fix for extracting attributes, they often fail when the input does not conform to strict formatting rules. HTML is notorious for inconsistent whitespace, varying quote styles (single vs. double), and self-closing tags that differ across browsers. A regex pattern designed to match src="..." could easily miss an image with src='...' or break if the attribute appears on multiple lines or contains comments within the tag.

In the context of a Laravel application, the standard way to handle this is by leveraging the DOMDocument class. This built-in PHP extension provides a robust parser that understands HTML structure. You instantiate a DOMDocument, load your string into it, and then query for the first matching node.

Here is how you would implement this using DOMDocument:

$htmlString = '<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" /> <p>Some text</p><img src="/other/path.png" />';

// Create a new DOMDocument instance
$dom = new DOMDocument();

// Load the HTML string. Note: We must suppress warnings for invalid HTML
libxml_use_internal_errors(true);
$dom->loadHTML($htmlString, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();

// Select the first <img> tag
$images = $dom->getElementsByTagName('img');

if ($images->length > 0) {
    $firstImage = $images[0];
    
    // Get the src attribute
    $srcValue = $firstImage->getAttribute('src');
    
    // Assign to variable as requested
    $foo = $srcValue; 
    
    echo "$foo"; // Outputs: /images/image.jpg
}

The critical step here is handling libxml_use_internal_errors(true). By default, if the HTML string contains malformed tags (which news stories often do), DOMDocument will throw warnings that can crash your script. Enabling internal error handling allows the parser to continue despite imperfections in the source text. The flags LIBXML_HTML_NOIMPLIED and LIBXML_HTML_NODEFDTD are also essential; they prevent the parser from adding a default <html> root element or DOCTYPE declaration, ensuring that $images->length correctly reflects the actual number of image tags in your input string.

Once you have the first node via $images[0], the getAttribute('src') method returns the raw value stored in the attribute. This handles dynamic content perfectly because it reads whatever is currently in the document, regardless of whether the path starts with a slash, includes query parameters, or points to an external domain.

If you are working within a larger Laravel project, you might encounter scenarios where DOMDocument feels too heavy for simple tasks. In those cases, packages like symfony/dom-crawler offer a more convenient syntax via the Crawler class, which simplifies querying without needing to manage DOM nodes manually. However, for a single string operation inside a request cycle or a background job, the native DOMDocument approach remains the most lightweight and dependency-free solution available in PHP 8+.

Remember that this method is sensitive to the case of the tag name if you were searching by string comparison, but since we are using getElementsByTagName('img'), the parser normalizes the case internally. This ensures reliability even if the source HTML uses <IMG> or <ImG>.

Our network