This should work, although it is not advisable to parse and manipulate HTML with regular expressions.
<?php
$in = '<img width="600" height="256" alt="javascript00" src="http://localhost/img/test.png" title="javascript00" class="aligncenter size-full wp-image-1973">';
$out = preg_replace(
'@<img( [^>]*?)\s*class="[^"]*"([^>]*?)>@',
'<p align="center"><img $1$2></p>',
$in
);
// if you need the image's class to be replaced with one class:
$out = preg_replace(
'@<img( [^*]+?)\s*class="[^"]*"([^>]*?)>@',
'<p align="center"><img class="aligncenter" $1$2></p>',
$in
);
There are other questions and answers on here that deal with the issue of why you should not use regexes to parse and manipulate HTML (which should be required reading before SO lets you create an account).
Assuming you are dealing with HTML you are retrieving from an external source that you have no control over, you would use DOMDocument's loadHTML method and suppress errors (if you have no control over the markup, this will handle quite malformed HTML, but it likes to emit errors even when it builds the document up just fine, so use @)
$dom = new DOMDocument;
// supress errors because DOMDocument will actually parse a malformed document
// even when it emits errors. this is something that is wrong with PHP.
@$dom->loadHTML('<img src="foo" class="bar">');
$xp = new DOMXPath($dom);
$node = $xp->query('body/img')->item(0);
$node->removeAttribute('class');
echo $dom->saveXML($node).PHP_EOL;
` around each img tag containing this class and delete this one. To resume, remove class of the img tag and add `
` :)
– CrazyMax Dec 26 '10 at 13:16