I am trying to manipulate a HTML content stored in a php variable.
The logic is as follows: The variable should be checked if it contains an <img ... /> tag and if a tag is found it should be wraped in an <a> tag and some parametres of the a tag should be read from the img tag.
The code in the end enables the fancybox plugin to all images, this can be done even via JS, but in my case I would like to have the content ready as it would be served to the visitor.

The initial content.

$content = 'This content has two images
<img src="/images/img1.jpg" alt="Image 1" />
<img src="/images/img2.jpg" alt="Image 2" />';

The final content

$content = 'This content has two images
    <a href="/images/img1.jpg" data-fancybox="image-popup" data-caption="Image 1">
        <img src="/images/img1.jpg" alt="Image 1" />
    <a href="/images/img2.jpg" data-fancybox="image-popup" data-caption="Image 2">
         <img src="/images/img2.jpg" alt="Image 2" />

Thank you!

$content = 'This content has two images
<img src="/images/img1.jpg" alt="Image 1" />
<img src="/images/img2.jpg" alt="Image 2" />';

$content = preg_replace('/\<img src="([^\"]+)" alt="([^\"]+)" \/>/',
    '<a href="\\1" data-fancybox="image-popup" data-caption="\\2">
        <img src="\\1" alt="\\2" />
    </a>', $content);


Thank you @AndrisP
This code works well, but it may needs some improvements.

In some cases the editor of the website puts some other parameters to the image (width, height)
on this cases you code does not work.

Could the above suggestion be improved?!

Another way - create document object and manipulate any element and its attributes e.g.


$content = '<!DOCTYPE html>
    <title>PAGE TITLE</title>
    <p>This content has two images</p>
        <img src="/images/img1.jpg" alt="Image 1" />
        <img src="/images/img2.jpg" alt="Image 2" />

$doc = new DOMDocument();

// prepare document object ...

echo $doc->saveHTML();


Someone else helped me to fond a solution.
Here is all the logic.

$source = '
  <img src="1.jpg"/>' . "\n" . '
  <img src="2.jpg" alt="2" />' . "\n" . '
  <img name="omg" src="3" asd="sdfgf" alt="2.jpg">' . "\n" . '
  <img src="4.jpg" alt="4" width="1107" height="1626"/>' . "\n" . '
  <img src="5.jpg" id="zz" alt="5" >' . "\n" . '
  <img src="6.jpg" alt="6" width="1229" height="922" />' . "\n" . '
  <img src="7.jpg" alt="7"/>' . "\n" . '
  <img src="8.jpg" alt="8" width="807" height="1117">

$pattern = '~(<img .*?src="([^"]+)" ?.*?(alt="([^"]+)")?.*?>)~';
$replacement = '<a href="$2" data-fancybox="image-popup" data-caption="$4">$1</a>';

$result = preg_replace($pattern, $replacement, $source);

echo 'SOURCE:<br />' . nl2br(htmlspecialchars($source)) . '<br /><br /><br />';
echo 'RESULT:<br />' . nl2br(htmlspecialchars($result));