Regex, as is mentioned many times daily here on SO, is not the best tool for HTML manipulation - luckily we have the DOMDocument object!
If you're supplied with just that string you can make the changes like so:
$orig = ' <a href="http://test.html" class="watermark" target="_blank">
<img width="399" height="4652" src="http://test.html/uploads/2013/10/10.jpg" class="aligncenter size-full wp-image-78360">
</a>';
$doc = new DOMDocument();
$doc->loadHTML($orig);
$anchor = $doc->getElementsByTagName('a')->item(0);
if($anchor->getAttribute('class') == 'watermark')
{
$anchor->setAttribute('class','fancybox');
$img = $anchor->getElementsByTagName('img')->item(0);
$currSrc = $img->getAttribute('src');
$img->setAttribute('src',preg_replace('/(\.[^\.]+)$/','_new$1',$currSrc));
}
$newStr = $doc->saveHTML($anchor);
Else if you're using a full document HTML source:
$orig = '<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<a href="http://test.html" class="watermark" target="_blank">
<img width="399" height="4652" src="http://test.html/uploads/2013/10/10.jpg" class="aligncenter size-full wp-image-78360">
</a>
<span>random</span>
<a href="http://test.html" class="watermark" target="_blank">
<img width="399" height="4652" src="http://test.html/uploads/2013/10/10.jpg" class="aligncenter size-full wp-image-78360">
</a>
<a href="#foobar" class="gary">
<img src="/imgs/yay.png" />
</a>
</body>
</html>';
$doc = new DOMDocument();
$doc->loadHTML($orig);
$anchors = $doc->getElementsByTagName('a');
foreach($anchors as $anchor)
{
if($anchor->getAttribute('class') == 'watermark')
{
$anchor->setAttribute('class','fancybox');
$img = $anchor->getElementsByTagName('img')->item(0);
$currSrc = $img->getAttribute('src');
$img->setAttribute('src',preg_replace('/(\.[^\.]+)$/','_new$1',$currSrc));
}
}
$newStr = $doc->saveHTML();
Although for brain exercise, I've provided a regex solution as that was the original question, and sometimes DOM docs can be overkill amounts of code (though still preferable)
$newStr = preg_replace('#<a(.+?)class="watermark"(.+?)<img(.+?)src="(.+?)(\.[^.]+?)"(.*?>.*?</a>)#s','<a$1class="fancybox"$2<img$3src="$4_new$5"$6',$orig);