Reputation: 20444
I have a string that contains an image in html format. Ie..
<img title="imagetitle1" src="www.example.com/image1.gif" height="420" width="340" />
I need to strip everything from it with the exception of the url of the src. Since we don't know what the title will be and thus cannot use str_replace
, how do we do this.
Upvotes: 0
Views: 70
Reputation: 227240
When parsing HTML data, I like to use DOMDocument
instead of a RegEx.
$data = 'Test data src="A" <img title="imagetitle1" src="www.example.com/image1.gif" height="420" width="340" />More data';
$DOM = new DOMDocument;
$DOM->loadHTML($data);
$xPath = new DOMXPath($DOM);
$img = $xPath->query('//img[@title="imagetitle1"]');
echo $img->item(0)->getAttribute('src');
Demo: http://codepad.org/bv6Ivnuy
Upvotes: 3
Reputation: 4716
With regex, you can do this:
$input = '<img title="imagetitle1" src="www.example.com/image1.gif" height="420" width="340" />';
if (preg_match('/src\\=\\"(.*?)\\"/m', $input, $matches)) {
echo $matches[1];
}
//output
www.example.com/image1.gif
Upvotes: 2