我可以str_replace在另一个文件中吗?

时间:2012-05-22 20:49:12

标签: php str-replace

我正在处理一个应该替换另一个文件中的变量的文件。到目前为止我试过了:

$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是数据库中需要替换为prefix_ $ dir的表。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您忘记再次写入该文件。

// 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";
相关问题