0

ファイル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クラスを試してみましたが、特殊文字のエンコードに問題があります。

例:

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

2 に答える 2

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();
于 2012-10-06T16:20:06.633 に答える
1

HTML の解析に正規表現を使用しないでください。

しかし、本当にしたい場合は、この正規表現を使用する必要があります >>

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

このデモを確認してください。

于 2012-10-06T16:13:44.700 に答える