我想在php中编写一个脚本来扫描html文档,并根据它找到的内容向元素添加新标记.更具体地说,我是扫描文档,并且每个元素都搜索CSS标记"float:right/left",如果找到它,它会添加align ="right/left"(基于它找到的内容).例:
<img alt="steve" src="../this/that" style="height: 12px; width: 14px; float: right"/>
变
<img alt="steve" src="../this/that" align="right" style="height: 12px; width: 14px; float: right"/>
$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');
Run Code Online (Sandbox Code Playgroud)
编辑:
当'float:'和'right'之间没有确定的空间量时,有几种选择:
//img[starts-with(normalize-space(substring-after(@style,'float:')),'right')]//img[contains(@style,'float:'],然后检查$node->getAttribute()实际发生的事情..
$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');
Run Code Online (Sandbox Code Playgroud)