转义 PHP 脚本中的字面量 <?php 和 <?

9
我正在使用PHP将php.ini模板化。我有一个脚本,使用CLI PHP脚本从模板生成httpd.conf、apachectl和php.ini来设置开发环境。不幸的是,在php.ini中(在注释中)有文字<?<?php。有没有可能以某种方式转义它们,使得php不会将其解释为普通的PHP转义序列?
目前我的解决方法是将它们包装在一个真正的PHP转义序列中,将它们输出为字符串,就像这样:
; This directive determines whether or not PHP will recognize code between
; <?php echo "<? and ?>" ?> tags as PHP source which should be processed as such. It's been
; recommended for several years that you not use the short tag "short cut" and
; instead to use the full <?php echo "<?php and ?>" ?> tag combination. With the wide spread use
;
3个回答

12
这个内容的翻译如下:

这个:

<?php echo "<?php"; ?>

将输出:

<?php

2
行。真的没有办法真正逃避 <? 吗? - rinogo
2
不行。没有办法做到。 - gahooa

3
您可以将整个ini文件用heredoc包裹起来,如下所示:
<?php 
echo <<< EOF
<?php echo "stuff inside php tag"; ?>
EOF;
?>

当输出时,不会在页面中呈现,但会出现在页面源代码中。
或者你可以使用HTML编码来处理标签。

&lt;?php echo 'this'; ?&gt;

我认为后者更适合你。
如果那不起作用,你可以使用ASCII编码,这方面我不是很了解。


3
“EOF type thingy which I don't know the name of” -> “Heredoc” - Charles
1
HTML编码只有在输出为HTML时才有效。但这不是HTML,而是php.ini文件。 - nohat
@nohat,将heredoc的值存储在变量中并保存到文件、.ini或其他地方是不是可能的呢? - andho

-1
一个快速且简单的解决方案是在php.ini中搜索并替换所有注释中的<?php标记为唯一标识符,文件解析完成后,再将这些唯一标识符替换回相应的php标记。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接