Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex & PHP - isolate src attribute from img tag

Tags:

string

regex

php

With PHP, how can I isolate the contents of the src attribute from $foo? The end result I'm looking for would give me just "http://example.com/img/image.jpg"

$foo = '<img class="foo bar test" title="test image" src="http://example.com/img/image.jpg" alt="test image" width="100" height="100" />'; 
like image 621
Jeff Avatar asked Jan 22 '10 21:01

Jeff


1 Answers

If you don't wish to use regex (or any non-standard PHP components), a reasonable solution using the built-in DOMDocument class would be as follows:

<?php     $doc = new DOMDocument();     $doc->loadHTML('<img src="http://example.com/img/image.jpg" ... />');     $imageTags = $doc->getElementsByTagName('img');      foreach($imageTags as $tag) {         echo $tag->getAttribute('src');     } ?> 
like image 193
John Parker Avatar answered Oct 02 '22 12:10

John Parker