编辑文件中的 php 代码和变量


Edit php code and variables in file

我有一个带有注释和代码的php文件。

<?php
// Some comments
define('THING', 'thing1');
$variable = 'string1';
if ($statement === true) { echo 'true1'; }

我想知道编辑此文件以更改变量并吐出包含更改的文件新版本的最佳方法。

<?php
// Some comments
define('THING', 'thing2');
$variable = 'string2';
if ($statement === true) { echo 'true2'; }

该文件相当大。我可以编写一个函数,将大量字符串加在一起进行输出,但是我与注释等有关的所有转义都将令人头疼。

我正在考虑包含该文件,但这只允许在另一个类中使用它的变量。

到目前为止,我唯一能想到的就是制作文件的"骨架"版本(下图),将我要更改的变量写入文件中。我可以分配它们,但实际上像上述任何一个示例一样将其全部转储回文件中都逃脱了我。

最好的方法?

<?php
// Some comments
define('THING', $thing);
$variable = $string;
if ($statement === true) { echo $true; }

我打算回应@Prisoner上面的评论,但我看到你提到你正在限制工作。您可以使用strtr()执行基本的模板,如下所示:

<?php
$template = <<<'STR'
hi there {{ name }}
it's {{ day }}. how are you today?
STR;
$vars = [
    '{{ name }}' => 'Darragh',
    '{{ day }}'  => date('l'),
];
$result = strtr($template, $vars);

这将产生以下字符串:

"hi there Darragh
it's Monday. how are you today?"

然后,您可以将结果写入文件,回显它等。

对于上面的具体示例:

<?php
$template = <<<'STR'
<?php
define('THING', '{{ const }}');
$variable = '{{ variable }}';
if ($statement === true) { echo '{{ echo }}'; }
STR;
$vars = [
    '{{ const }}'    => 'thing1',
    '{{ variable }}' => 'string1',
    '{{ echo }}'     => 'true1',
];
echo $result = strtr($template, $vars);

收益 率:

"<?php
define('THING', 'thing1');
$variable = 'string1';
if ($statement === true) { echo 'true1'; }"

希望这对:)有所帮助

听起来像是简单字符串替换问题的一种形式。

如果您需要将新变量保存到新文件中,而"骨架"文件保留为有效的PHP语法,则可能需要以某种方式命名模板变量,以便可以唯一且正确地找到和替换它们。你基本上是在创建自己的简单模板语言。

因此,您的模板文件可能如下所示:

<?php
// Some comments
define('THING', $TEMPLATE_VARIABLE['thing']);
$variable = $TEMPLATE_VARIABLE['string'];
if ($statement === true) { echo $TEMPLATE_VARIABLE['true']; }

以及替换模板变量的代码

// Read the template file
$str = file_get_contents($template_file_path);
// Make your replacements
$str = str_replace("$TEMPLATE_VARIABLE['thing']", 'thing1', $str);
$str = str_replace("$TEMPLATE_VARIABLE['string']", 'string1', $str);
$str = str_replace("$TEMPLATE_VARIABLE['true']", 'true1', $str);
// Save as a new file
if (file_put_contents($output_file_path, $str, LOCK_EX) === FALSE) {
    throw new Exception('Cannot save file. Possibly no write permissions.');
}

如果你不介意你的模板文件不是有效的PHP,你当然可以疯狂地使用你的模板,例如 define('THING', ~!@#$THING%^&*);

最后说明:无论如何,如果你能负担得起时间和精力来重构,请这样做。您显示的代码片段不是管理可能在多个位置使用的变量的最佳方法(它们实际上是应用程序设置吗?实际上,最好的办法是拥有一个定义所有这些变量的配置文件。

// In the config file
define('MESSAGE_TO_SHOW_IF_TRUE', 'true');
define('DEFAULT_USER_NAME', 'lala');
// In the application file
if ($statement === TRUE) { echo MESSAGE_TO_SHOW_IF_TRUE; }
$name = DEFAULT_USER_NAME;