我正在寻找在 php 中编写一个脚本来扫描 html 文档并根据它找到的内容向元素添加新标记。更具体地说,我是扫描文档并为每个元素搜索CSS标记“float:right/left”,如果找到它,它会添加align =“right/left”(基于它找到的内容)。
例子:
<img alt="steve" src="../this/that" style="height: 12px; width: 14px; float: right"/>
becomes
<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');
edit:
当“float:”和“right”之间的空间大小不确定时,有几种选择:
- 使用 XPath 1.0:
//img[starts-with(normalize-space(substring-after(@style,'float:')),'right')]
- 只需对 float 进行简单的检查即可
//img[contains(@style,'float:']
,并检查$node->getAttribute()
之后实际发生的事情。
- 将 preg_match 导入到方程中(这是最近向我指出的(感谢戈登),但在这种情况下,恕我直言,这是最不喜欢的解决方案):
.
$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');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)