4

PHP を使用して、ファイルの内容から特定の ID を持つ要素を検索し、その内容を置き換えてから、変更をファイルに保存したいと考えています。HTML を読み込んで再度保存することはできますが、「検索と置換」に問題があります (現在 preg_replace を使用しようとしています)。

これが私がこれまでに持っているものです:

<?php
// read in the content
$file = file_get_contents('file.php');

// parse $file, looking for the id.
$replace_with = "id='" . 'myID' . "'>" . $replacement_content . "<";
if ($updated = preg_replace('/id\=\"myID\"\>.*?\</', $replace_with, $file)) {   
    // write the contents of $file back to index.php, and then refresh the page.
    file_put_contents('file.php', $updated);
}

ただし、コンテンツを正常にロードして書き出しますが (別のファイルに書き込んでテストしました)、$updated は実際には変更されないようです。

何か案は?

4

3 に答える 3

10

DOMDocumentこれには PHP を使用できます。

$html = new DOMDocument(); 
$html->loadHTMLFile('file.php'); 
$html->getElementById('myId')->nodeValue = 'New value';
$html->saveHTMLFile("foo.html");
于 2010-12-03T21:56:25.840 に答える
1

エスケープの問題がいくつか発生していると思います;-)

これを試して:

$replace_with = 'id="myID">' . $replacement_content . '</';
if ($updated = preg_replace('#id="myID">.*?</#Umsi', $replace_with, $file)) {   
    // write the contents of $file back to index.php, and then refresh the page.
    file_put_contents('file.php', $updated);
}
于 2010-12-03T22:06:42.787 に答える
1

なぜ「=」をエスケープしているのか考えただけで、そうあるべきです/id=\"myID\"\>.*?\</

于 2010-12-03T21:55:04.593 に答える