使用PHP替换纯文本变量的最佳方法

nic*_*ckf 8 php variables substitution

采用包含PHP样式变量的纯文本(不是PHP代码),然后替换变量值的最佳方法是什么.这有点难以描述,所以这是一个例子.

// -- 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.";
Run Code Online (Sandbox Code Playgroud)

我一直在考虑使用正则表达式,或者也许eval(),虽然我不确定哪个最简单.这个脚本只会在本地运行,因此对安全问题的担忧eval()并不适用(我认为?).

我还要补充一点,我可以使用以下方法将所有必要的变量放入数组get_defined_vars():

$allVars = get_defined_vars();
echo $pet;             // "lamb"
echo $allVars['pet'];  // "lamb"
Run Code Online (Sandbox Code Playgroud)

Tom*_*lak 11

正则表达式很容易.并且它不关心eval()会考虑语法错误的事情.

这是找到PHP样式变量名称的模式.

\$\w+
Run Code Online (Sandbox Code Playgroud)

我可能会采用这种通用模式并使用PHP数组来查找我找到的每个匹配项(using(preg_replace_callback()).这样正则表达式只需要应用一次,从长远来看速度更快.

$allVars = get_defined_vars();
$file = file_get_contents('myFile.txt');

// unsure if you have to use single or double backslashes here for PHP to understand
preg_replace_callback ('/\$(\w+)/', "find_replacements", $file);

// replace callback function
function find_replacements($match)
{
  global $allVars;
  if (array_key_exists($match[1], $allVars))
    return $allVars[$match[1]];
  else
    return $match[0];
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上,就是这个(来自php手册):[a-zA-Z_\x7f-\xff] [a-zA-Z0-9_\x7f-\xff]* (2认同)

Gre*_*reg 5

如果它来自可靠的来源,你可以使用(戏剧性停顿)eval()(来自观众的恐怖喘息).

$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
Run Code Online (Sandbox Code Playgroud)