用PHP更新文本文件的一部分


Updating portion of text file with PHP

是否可以用PHP替换部分文本或HTML文件?我正在使用preg_match将文件的一部分加载到文本编辑器中,只提取某些标记之间的文本。现在,当完成编辑时,我想用所做的更改更新相同的文件,并替换以前加载的相同零件。

因为您使用的是preg_match,所以您可以在编辑后使用preg_replace并将其存储到文件中。

例如,如果您正在为此加载UI,那么您可能会在file1.php上执行此操作

$data = file_get_contents($filename);
//do regex here
$values = preg_match($pattern,$data);
//do necessary display here for the form I assume

然后在接收表单请求的file2.php上,您会做同样的事情

$data = file_get_contents($filename);
//compose the string to you will have to replace to the pattern
$data = preg_replace($pattern,$replace,$data);
//then write to the same file
file_put_contents($filename,$data);

这些只是理论上的,请参阅php手册以获得正确的语法或参数