tags:

views:

57

answers:

2

Let's say I have a string contaning HTML markup with many img tags that look like this:

<img src="data/images/original/3.png" alt="" />

I need a regular expression that would change all images to have paths like this:

<img src="/utils/locate-image?path=data%2Fmedia%2Fimages%2Foriginal%2F3.png" alt="" />

I'm not very good with regular expression so I would appreciate some code example that can do this?

+3  A: 

Don't use regular expressions for this. The Simple HTML DOM parser should be perfect for the job.

It should be as easy as this:

foreach($html->find('img') as $e) {
  $e->src = "insert modified src here";
}

echo $html;
Pekka
But won't it be slower with HTML DOM?
Richard Knop
Maybe. Do you want fast or correct?
Tim Pietzcker
That would be `$e->src = '/utils/locate-image?path=' . urlencode($e->src);` is guess.
jensgram
+3  A: 

Don't use regular expressions for this. PHP's native DOM parser should be perfect for the job.

$dom = new DOMDocument;
$dom->loadHTML('<img src="foo" alt=""/>');
$images = $dom->getElementsByTagName('img');
foreach($images as $image) {
    $image->setAttribute('src', 'bar');
    echo $dom->saveXML($image);
}

echoes <img src="bar" alt=""/>

Gordon
+1 (despite blatant copyright violations in the 1st paragraph! :) because it doesn't require an external library.
Pekka
@Pekka sue me :D
Gordon
@Gordon can you say *"Abmahnung"*? :D
Pekka
@Pekka cant hear you lalalalalalala ;)
Gordon