【问题标题】:preg_replace: replace a html tag valuepreg_replace:替换一个html标签值
【发布时间】:2012-10-06 16:10:15
【问题描述】:

需要改变一个标签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);

【问题讨论】:

标签: php regex preg-replace


【解决方案1】:

有了 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();

【讨论】:

  • 可行,但现在我遇到了编码特殊字符的问题。
【解决方案2】:

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

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

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

检查this demo

【讨论】:

  • @MiguelBorges - 我已经更新了我的答案并添加了一个演示链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 2013-04-23
  • 2011-12-07
  • 2020-06-25
相关资源
最近更新 更多