php - 我可以将 str_replace 放在另一个文件中吗?

标签 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是数据库中的一个表,需要用前缀_$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/

相关文章:

php - 简单 : How to replace "all between" with php?

php - 如何使用 php 读取文本文件并将这些值插入数据库

python - 如何在Python 3中显示单词中的前3个字母,但用 "-"破折号替换单词的其余部分

PHP 错误报告 - 使用 "^"字符和 "~"字符

php - 计算网站的超链接

php - 如何替换上传文件文件名中的空格

javascript - 如何替换字符串中的 $1 , $2

PHP-替换字符串中的字符

php - 在 json 模式数据中包含 php 变量 - WordPress 站点 - 无效的 json 错误

php - 更改 CSS onclick 函数 javascript