preg_replace:替换html标记值

时间:2012-10-06 16:10:15

标签: php regex preg-replace

需要在文件html中更改标记html的值。 我试图使用函数preg_replace()但我无法改变任何东西。

html文件:

 ...
 <div id="phrase_of_day">
     <div>
         <span class="icon quote"></span>
         <h1>Frase do Dia</h1>
         <blockquote><p>value to change</p></blockquote>
     </div>
 </div>
 ...

我试试这个:

$url = '../index.html';

$file = file_get_contents($url);

$o = preg_replace('/.*<div id="phrase_of_day">.*<blockquote><p>(\w+)<\/p><\/blockquote>/','hello world', $file);

file_put_contents('test.html', $o);

有人知道我哪里错了吗?

更新

我尝试使用DOMDocument类,就像建议的Madara Uchiha一样,但现在我遇到了编码特殊字符的问题。

示例:

origin: <h1>Gerar Parágrafos</h1>
after: <h1>Gerar Par&Atilde;&iexcl;grafos</h1>

代码:

libxml_use_internal_errors(true);
$document = new DOMDocument('1.0', 'UTF-8');
$document->loadHTMLFile($url);
$document->encoding = 'UTF-8';

$blockquote = $document
    ->getElementById("phrase_of_day") //Div
    ->getElementsByTagName("blockquote")->item(0);

$new_value = new DOMElement("p", "New Value for Element");
$blockquote->replaceChild($new_value, $blockquote->childNodes->item(0));

$document->saveHTMLFile('test.html');
libxml_use_internal_errors(false);

2 个答案:

答案 0 :(得分:3)

使用DOM,就像一个理智的人:

<?php

$html = <<<HTML
 <div id="phrase_of_day">
     <div>
         <span class="icon quote"></span>
         <h1>Frase do Dia</h1>
         <blockquote><p>value to change</p></blockquote>
     </div>
 </div>
HTML;

$document = new DOMDocument();
$document->loadHTML($html);

$blockquote = $document
    ->getElementById("phrase_of_day") //Div
    ->getElementsByTagName("blockquote")->item(0);

$new_value = new DOMElement("p", "New Value for Element");
$blockquote->replaceChild($new_value, $blockquote->childNodes->item(0));

echo $document->saveHTML();

答案 1 :(得分:1)

您不应该使用正则表达式来解析HTML。

但是,如果你真的想,那么你应该使用这个正则表达式&gt;&gt;

$o = preg_replace(
  '/(<div id="phrase_of_day">.*?<blockquote><p>)([^<]+)(<\/p><\/blockquote>)/s', 
  '$1hello world$3',
  $file);

检查 this demo

相关问题