code_junkie

Best way to substitute variables in plain text using PHP

Nov 12th, 2011
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. // -- myFile.txt --
  2. Mary had a little $pet.
  3.  
  4. // -- parser.php --
  5. $pet = "lamb";
  6. // open myFile.txt and transform it such that...
  7. $newContents = "Mary had a little lamb.";
  8.  
  9. $allVars = get_defined_vars();
  10. echo $pet; // "lamb"
  11. echo $allVars['pet']; // "lamb"
  12.  
  13. $text = 'this is a $test'; // single quotes to simulate getting it from a file
  14. $test = 'banana';
  15. $text = eval('return "' . addslashes($text) . '";');
  16. echo $text; // this is a banana
  17.  
  18. $w+
  19.  
  20. $allVars = get_defined_vars();
  21. $file = file_get_contents('myFile.txt');
  22.  
  23. // unsure if you have to use single or double backslashes here for PHP to understand
  24. preg_replace_callback ("$w+", "find_replacements", $file);
  25.  
  26. // replace callback function
  27. function find_replacements($match)
  28. {
  29. global $allVars;
  30. if (array_key_exists($match[0], $allVars)
  31. return $allVars[$match[0]];
  32. else
  33. return $match[0];
  34. }
  35.  
  36. $allVars = get_defined_vars();
  37. $file = file_get_contents('myFile.txt');
  38.  
  39. foreach ($allVars as $var => $val) {
  40. $file = preg_replace("@\$" . $var . "([^a-zA-Z_0-9x7f-xff]|$)@", $val . "\1", $file);
  41. }
  42.  
  43. // -- myFile.txt --
  44. Mary had a little %pet%.
  45.  
  46. // -- parser.php --
  47. $pet = "lamb";
  48. $fileName = myFile.txt
  49.  
  50. $currentContents = file_get_contents($fileName);
  51.  
  52. $newContents = str_replace('%pet%', $pet, $currentContents);
  53.  
  54. // $newContents == 'Mary had a little lamb.'
  55.  
  56. //myFile.txt
  57. Mary had a little <?= $pet ?>.
  58.  
  59. //parser.php
  60.  
  61. $pet = "lamb";
  62. ob_start();
  63. include("myFile.txt");
  64. $contents = ob_end_clean();
  65.  
  66. echo $contents;
  67.  
  68. Mary had a little lamb.
  69.  
  70. $text = file_get_contents('/path/to/myFile.txt'); // "Mary had a little $pet."
  71. $allVars = get_defined_vars(); // array('pet' => 'lamb');
  72. $translate = array();
  73.  
  74. foreach ($allVars as $key => $value) {
  75. $translate['$' . $key] = $value; // prepend '$' to vars to match text
  76. }
  77.  
  78. // translate is now array('$pet' => 'lamb');
  79.  
  80. $text = strtr($text, $translate);
  81.  
  82. echo $text; // "Mary had a little lamb."
Add Comment
Please, Sign In to add comment