0

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.

0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.