matt
matt

Reputation: 2352

Replace <div> tag containing a sourcefile attribute with an <img> tag containing the captured url

I have this string:

$string = '<div class="displayEmbededImage" sourcefile="http://example.com/images/myImage.jpg" style="width:200px;"><p>Some text goes here</p></div>';

I need a regex that will will select the content of sourcefile and return it like this:

$parern = '/<div(.*)sourcefile="([^"]+)"(.*)>(.*)<\/div>/s';
preg_replace($pattern, '<img src="$1">', $string);

That's what I have so far, but not getting it quite right yet.

Upvotes: 1

Views: 104

Answers (2)

Marc B
Marc B

Reputation: 360632

You do NOT use regex on html. Don't even try. Use DOM instead:

$d = new DOMdocument();
$d->loadHTML('... your html here ...');
$xp = new DOMXpath($d);
$res = $xp->query('//div[@class="displayEmbededImage"]');
$source = $res->item(0)->getAttribute('sourcefile');

Upvotes: 4

Tchoupi
Tchoupi

Reputation: 14681

You have a typo in your variable name, and you are not using the right placeholder:

echo preg_replace($parern, '<img src="$2">', $string);

Upvotes: 2

Related Questions