Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to substitute variables in plain text using 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.";

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?).

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"
like image 857
nickf Avatar asked Nov 12 '08 07:11

nickf


2 Answers

Regex would be easy enough. And it would not care about things that eval() would consider a syntax error.

Here's the pattern to find PHP style variable names.

\$\w+

I would probably take this general pattern and use a PHP array to look up each match I've found (using (preg_replace_callback()). That way the regex needs to be applied only once, which is faster on the long run.

$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];
}
like image 106
Tomalak Avatar answered Sep 23 '22 05:09

Tomalak


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
like image 30
Greg Avatar answered Sep 23 '22 05:09

Greg