【问题标题】:domdocument regex replace tagdomdocument 正则表达式替换标签
【发布时间】:2015-09-12 16:11:51
【问题描述】:

你好,我有一个这样的 php 正则表达式代码:

preg_replace('~<div\s*.*?(?:\s*class\s*=\s*"(.*?)"|id\s*=\s*"(.*?)\s*)?>~i','<div  align="center" class="$1" id="$2">', "html source code");

现在我要做的是替换源 html 代码中的所有标签,然后只保留 div 标签中的类和 id 并添加 align="center" 到它:
示例:
&lt;div style="border:none;" class="classbutton"&gt; will be replaced to &lt;div align="center" class="classbutton"&gt;

<div style="border:none;" class="classbutton" id="idstyle"> will be replaced to <div align="center" class="classbutton" id="idstyle">


我已经尝试了许多使用 php 正则表达式的代码,但似乎没有什么对我有用。所以如果有人可以帮助我或给我一个 domdocument 代码来解决这个问题。 提前致谢。

【问题讨论】:

  • 那是你真正的 HTML 吗?如果是这样,&lt;div 之间有一个空格。在这里也没有看到domdocument 的用法..
  • 我正在使用来自网站的 file_get_contents 进行获取
  • 然后我替换了网站的所有
    标签
  • 我正在使用如上所述的 php 正则表达式代码,但它不起作用,我听说 domdocument 可以解决我的问题,所以我要求有人给我一个 domdocument 替换我的 php 正则表达式代码跨度>
  • 这不是一个只有gives code 的网站。我们帮助解决编码问题。你试过使用domdocument 了吗? domdocument 是比正则表达式更好的方法。

标签: php regex preg-replace domdocument


【解决方案1】:

这里有一些 sn-p 可以帮助你:

$html = '<body><div style="border:none;" class="classbutton" id="idstyle">Some text</div></body>';            // Sample HTML string

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($dom);
$divs = $xpath->query('//div[@class="classbutton"]'); // Get all DIV tags with class "classbutton"

foreach($divs as $div) {                  // Loop through all DIVs found
   $div->setAttribute('align', 'center'); // Set align="center"
   $div->removeAttribute('style');        // Remove "style" attribute
}

echo $dom->saveHTML();                    // Save HTML (use $html = $dom->saveHTML();)

IDEONE demo

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签