如何在PHP中使用preg添加html属性 [英] How to use preg in php to add html properties

查看:85
本文介绍了如何在PHP中使用preg添加html属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个用php编写的脚本,该脚本可以扫描html文档,并根据发现的内容向元素添加新的标记.更具体地说,我要扫描文档,并针对每个元素搜索CSS标记"float:right/left",如果找到它,则会添加align ="right/left"(基于找到的内容). 示例:

I'm looking to write a script in php that scans an html document and adds new markup to a element based on what it finds. More specifically, I was it to scan the document and for every element it searches for the CSS markup "float: right/left" and if it locates it, it adds align="right/left" (based on what it finds). Example:

<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');

当"float:"和"正确",有几种选择:

When there is no certainty of amount of space between 'float:' & 'right', there are several options:

  1. 使用XPath 1.0://img[starts-with(normalize-space(substring-after(@style,'float:')),'right')]
  2. 只需对//img[contains(@style,'float:']这样的浮点数进行简单检查,然后使用$node->getAttribute()检查之后的实际情况.
  3. 将preg_match导入到equasion中(刚刚向我指出(感谢Gordon),但是在这种情况下,imho是最不受欢迎的解决方案):
  1. Use the XPath 1.0: //img[starts-with(normalize-space(substring-after(@style,'float:')),'right')]
  2. Just do a simple check for float like //img[contains(@style,'float:'], and check with $node->getAttribute() what actually comes afterwards.
  3. 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');

这篇关于如何在PHP中使用preg添加html属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆