$dom = new DOMDocument();
$dom->loadHTML($htmlstring);
$x = new DOMXPath($dom);
foreach($x->query("//img[contains(@style,'float: right']") as $node) $node->setAttribute('align','right');
foreach($x->query("//img[contains(@style,'float: left']") as $node) $node->setAttribute('align','left');
edit:
When there is no certainty of amount of space between 'float:' & 'right', there are several options:
- Use the XPath 1.0:
//img[starts-with(normalize-space(substring-after(@style,'float:')),'right')]
- Just do a simple check for float like
//img[contains(@style,'float:']
, and check with $node->getAttribute()
what actually comes afterwards.
- Import preg_match into the equasion (which was just recently pointed out to me (thanks Gordon), but in this case is imho the least favorite solution):
.
$dom = new DOMDocument();
$dom->loadHTML($htmlstring);
$x = new DOMXPath($dom);
$x->registerNamespace("php", "http://php.net/xpath");
$x->registerPHPFunctions('preg_match');
foreach($x->query("//img[php:functionString('preg_match','/float\s*:\s*right/',@style)]") as $node) $node->setAttribute('align','right');