Q:

Adding link tags and rel="lightbox" around images Regex

How can i change this example when i just got the <image> tag and i want to add link tags around them and the rel lightbox attribute as well?
i cant figure it out. I'm just not good with regular expressions at all. 
the example
$pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title="'.$post->post_title.'"$6>';

So in my case i have <img src="...." class="...." alt=".....">
and i need <a href="....." rel="lightbox" title="....."><img src="...." class="...." alt="....."></a>
How would i change this?
Thanks for help.

A:

It's unclear what you exactly want to do here, but I would utilize DOM for this task instead.
$doc = DOMDocument::loadHTML('
     <img src="www.foo.com/1.gif" class="foo" alt="...">
     <img src="www.bar.com/1.jpg" class="bar" alt="...">
     <img src="example.com/2.jpg" class="example" alt="...">   
');

foreach ($doc->getElementsByTagName('img') as $node) {
   $link = $node->ownerDocument->createElement('a');

   $a = $node->parentNode->insertBefore($link, $node);

   $a->setAttribute('href', $node->getAttribute('src'));
   $a->setAttribute('rel', 'lightbox');
   $a->setAttribute('title', 'some title');

   $a->appendChild($node);
}

echo $doc->saveHTML();

Output:
<a href="www.foo.com/1.gif" rel="lightbox" title="some title"><img src="www.foo.com/1.gif" class="foo" alt="..."></a>
<a href="www.bar.com/1.jpg" rel="lightbox" title="some title"><img src="www.bar.com/1.jpg" class="bar" alt="..."></a>
<a href="example.com/2.jpg" rel="lightbox" title="some title"><img src="example.com/2.jpg" class="example" alt="..."></a>

