您可以使用token_get_all()
從PHP文件 (例如,
<?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";
//$token[2] is line number of the string
}
}
你可以做一個非常骯髒的支票,它沒有被用來作爲數組索引的東西,如:
$fileLines = file('file.php');
//inside the loop and if
$line = $fileLines[$token[2] - 1];
if (false === strpos($line, "[{$token[1]}]")) {
//not an array index
}
但你真的很難正確地做到這一點,因爲有人可能已經編寫一些你可能不希望如:
$str = 'string that is not immediately an array index';
doSomething($array[$str]);
編輯 螞蟻P說,你可能會更好尋找周圍的令牌[
和]
對於這個答案的第二部分,而不是我的strpos
黑客,像這樣:
$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
}
+1永遠不知道這個功能。棒極了。 – cletus 2009-02-21 00:26:12
唯一的一點是,對於 $ _SESSION [「logsession」] 它實際上給了我 找到字符串「logsession」 這當然不是我想要的本地化。 – Ray 2009-02-21 00:33:14