Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- error_reporting(-1);
- ini_set('display_errors', true);
- $savedValues = [];
- $searchForVariableNames = ['$MetaKeys', '$MetaDesc'];
- foreach(['test2.php', 'test3.php'] as $filename) {
- $srcText = file_get_contents($filename);
- $tokens = token_get_all($srcText);
- // use this to visualize tokens...
- /* foreach($tokens as $token) {
- if(is_array($token)) {
- echo token_name($token[0]) . "\t" . $token[1] . "\t" . $token[2] . "\n";
- } else {
- echo ' > ' . $token . "\n";
- }
- } */
- for($x = 0; $x < count($tokens); $x++) {
- $token = $tokens[$x];
- if(is_array($token)) {
- if($token[0] === T_VARIABLE && in_array($token[1], $searchForVariableNames, true)) {
- // look ahead
- $y = $x;
- // if you really want to make it pretty, add all the possible token types here with a separate "no-save" path,
- // instead of assuming it will always be followed by T_CONSTANT_ENCAPSED_STRING ... else, this code will error out on eg.
- // $MetaDesc = $anotherVar;
- while(isset($tokens[$y]) && $tokens[$y][0] !== T_CONSTANT_ENCAPSED_STRING) {
- $y++;
- // reasonable limit
- if($y - $x >= 5) {
- throw new \Exception("Can't find value for token: {$token[1]} within a reasonable amount of tokens (started on line {$token[2]})");
- }
- };
- if(!isset($tokens[$y])) {
- 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.");
- }
- // now we have the variable-name token in $x and the value in $y
- // (probably)
- $savedValues[$filename] = $savedValues[$filename] ?? [];
- $savedValues[$filename][] = [
- $tokens[$x][1] => $tokens[$y][1]
- ];
- }
- }
- }
- }
- var_dump($savedValues);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement