我正在处理一个文件,该文件应该替换另一个文件中的变量。到目前为止我尝试过:
$File = "$dir/submit.php";
$fh = fopen($File, 'r') or die("Couldn't edit the Config-file. Please report to admin.");
$chosendb = str_replace('$chosendb = comments;','$chosendb = wuhuws_$dir;','$chosendb');
fclose($fh);
$dir 是用户输入。 comments是数据库中的一个表,需要用前缀_$dir替换。
我做错了什么?
最佳答案
您忘记再次写入文件。
// Read the file
$content = file_get_contents("$dir/submit.php");
// Do the editing
$content = str_replace('$chosendb = comments;','$chosendb = wuhuws_$dir;', $content);
// Save the file
file_put_contents("$dir/submit.php", $content);
但是,正如 Zerkms 所说(或者至少有意为之;-)),使用 PHP 编辑 PHP 通常是一个坏主意,特别是因为您会发现稍后很难调试您的脚本,因为它的代码会在运行时动态更改。
是否有任何原因导致您无法包含此文件并手动设置这些变量,例如:
// Include the file
require("$dir/submit.php");
// Edit the variable
$chosendb = "wuhuws_$dir";
关于php - 我可以将 str_replace 放在另一个文件中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10709958/