使用PHP在纯文本中替换变量的最佳方法 [英] Best way to substitute variables in plain text using PHP
问题描述
获取包含PHP样式变量的纯文本(不是PHP代码),然后替换该变量的值的最佳方法是什么.这有点难以描述,所以这里有个例子.
What's the best way to take some plain text (not PHP code) which contains PHP-style variables, and then substitute in the value of the variable. This is kinda hard to describe, so here's an example.
// -- myFile.txt --
Mary had a little $pet.
// -- parser.php --
$pet = "lamb";
// open myFile.txt and transform it such that...
$newContents = "Mary had a little lamb.";
我一直在考虑使用正则表达式,或者也许是eval()
,尽管我不确定哪一个最简单.该脚本仅将在本地运行,因此对安全性问题和eval()
的任何担心都不适用于(我认为吗?).
I've been considering using a regex or perhaps eval()
, though I'm not sure which would be easiest. This script is only going to be running locally, so any worries regarding security issues and eval()
do not apply (i think?).
我还要补充一点,就是可以使用get_defined_vars()
将所有必需的变量放入数组中:
I'll also just add that I can get all the necessary variables into an array by using get_defined_vars()
:
$allVars = get_defined_vars();
echo $pet; // "lamb"
echo $allVars['pet']; // "lamb"
推荐答案
If it's from a trusted source you can use (dramatic pause) eval() (gasps of horror from the audience).
$text = 'this is a $test'; // single quotes to simulate getting it from a file
$test = 'banana';
$text = eval('return "' . addslashes($text) . '";');
echo $text; // this is a banana
这篇关于使用PHP在纯文本中替换变量的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!