2012-06-25 42 views
0

我有文本常量的文件。我怎樣才能得到不變的名字和不變的價值。問題是恆定的值有時間空間。我讀的文件與file(),然後用foreach ...如何在文件中獲得常量名稱和常量值

例子:

define('LNG_UTF-8',   'Universal Alphabet (UTF-8)'); 
define('LNG_ISO-8859-1', 'Western Alphabet (ISO-8859-1)'); 
define('LNG_CustomFieldsName', 'Custom Field'); 
define('LNG_CustomFieldsType', 'Type'); 

我已經嘗試過:

獲得恆定的名字:

$getConstant1 = strpos($mainFileArray[$i], '(\''); 
$getConstant2 = strpos($mainFileArray[$i], '\',');    
$const = substr($mainFileArray[$i], $getConstant1 + 2, $getConstant2 - $getConstant1 - 2); 

獲得恆定值

$position1 = strpos($file[$i], '\','); 
$position2 = strpos($file[$i], '\');'); 

$rest = substr($file[$i], $position1 + 3, $position2 - $position1 - 2); 

但不工作時,空間或','...

我怎樣才能使這總是工作?

+0

爲什麼你不能簡單'包括'文件並使用常量作爲常量? – deceze

回答

1

正則表達式匹配,這將是這樣的:

preg_match("/define\(\s*'([^']*)'\s*,\s*'([^']*)'\s*\)/i", $line, $match); 
echo $match[1], $match[2]; 

參見http://rubular.com/r/m9plE2qQeT

但是,如果字符串單引號',不包含轉義引號,只有工作,該字符串不是串聯等。例如,這將打破:

define('LNG_UTF-8', "Universal Alphabet (UTF-8)"); 
define('LNG_UTF-8', 'Universal \'Alphabet\' (UTF-8)'); 
define('LNG_UTF-8', 'Universal Alphabet ' . '(UTF-8)'); 
// and many similar 

爲了使至少前兩項工作,您應該根據PHP解析規則使用token_get_all解析 PHP文件,然後檢查所得到的標記並提取所需的值。
要使所有案例都能正常工作,您需要實際評估的PHP代碼,即include該文件,然後在PHP中簡單地訪問常量作爲常量。