You can use token_get_all() to get all tokens from a PHP file for example.
<?php $fileStr = file_get_contents('file.php'); foreach (token_get_all($fileStr) as $token) { if ($token[0] == T_CONSTANT_ENCAPSED_STRING) { echo "found string {$token[1]}\r\n";
You can do a really dirty check that it is not used as an array index with something like:
$fileLines = file('file.php'); //inside the loop and if $line = $fileLines[$token[2] - 1]; if (false === strpos($line, "[{$token[1]}]")) { //not an array index }
but you will really try to do it right, because someone can write something that you do not expect, for example:
$str = 'string that is not immediately an array index'; doSomething($array[$str]);
Edit As Ant P says, you will probably be better off looking [ and ] in the surrounding tokens for the second part of this answer, and not for my strpos hack, something like this:
$i = 0; $tokens = token_get_all(file_get_contents('file.php')); $num = count($tokens); for ($i = 0; $i < $num; $i++) { $token = $tokens[$i]; if ($token[0] != T_CONSTANT_ENCAPSED_STRING) { //not a string, ignore continue; } if ($tokens[$i - 1] == '[' && $tokens[$i + 1] == ']') { //immediately used as an array index, ignore continue; } echo "found string {$token[1]}\r\n"; //$token[2] is line number of the string }
source share