Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. <?php
  2. error_reporting(-1);
  3. ini_set('display_errors', true);
  4.  
  5. $savedValues = [];
  6. $searchForVariableNames = ['$MetaKeys', '$MetaDesc'];
  7.  
  8. foreach(['test2.php', 'test3.php'] as $filename) {
  9. $srcText = file_get_contents($filename);
  10. $tokens = token_get_all($srcText);
  11.  
  12. // use this to visualize tokens...
  13. /* foreach($tokens as $token) {
  14. if(is_array($token)) {
  15. echo token_name($token[0]) . "\t" . $token[1] . "\t" . $token[2] . "\n";
  16. } else {
  17. echo ' > ' . $token . "\n";
  18. }
  19. } */
  20.  
  21. for($x = 0; $x < count($tokens); $x++) {
  22. $token = $tokens[$x];
  23. if(is_array($token)) {
  24.  
  25. if($token[0] === T_VARIABLE && in_array($token[1], $searchForVariableNames, true)) {
  26. // look ahead
  27. $y = $x;
  28.  
  29. // if you really want to make it pretty, add all the possible token types here with a separate "no-save" path,
  30. // instead of assuming it will always be followed by T_CONSTANT_ENCAPSED_STRING ... else, this code will error out on eg.
  31. // $MetaDesc = $anotherVar;
  32. while(isset($tokens[$y]) && $tokens[$y][0] !== T_CONSTANT_ENCAPSED_STRING) {
  33. $y++;
  34.  
  35. // reasonable limit
  36. if($y - $x >= 5) {
  37. throw new \Exception("Can't find value for token: {$token[1]} within a reasonable amount of tokens (started on line {$token[2]})");
  38. }
  39. };
  40.  
  41. if(!isset($tokens[$y])) {
  42. throw new \Exception("Reached the end of file with no string for token: " . $token[1] . " (started on line " . $token[2] . "). Probably set to a not-a-string.");
  43. }
  44.  
  45. // now we have the variable-name token in $x and the value in $y
  46. // (probably)
  47.  
  48. $savedValues[$filename] = $savedValues[$filename] ?? [];
  49. $savedValues[$filename][] = [
  50. $tokens[$x][1] => $tokens[$y][1]
  51. ];
  52.  
  53. }
  54. }
  55.  
  56. }
  57. }
  58.  
  59. var_dump($savedValues);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement