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 は実際には変更されないようです。
何か案は?