可靠地从文件中检索 PHP 常量


Reliably retrieve PHP constant from a file

最新编辑:
好吧,我想出了相当"可靠"的:)以(便携式)功能的形式提供解决方案,但由于这里的一些人因不了解问题而感到厌烦并阻止了这个问题(军事解决方案:杀死您不理解的内容),我无法在此处发布。可惜。

我有一组文件,其中包含常量,如下所示。

定义("LNG_GSU_LNK_LBL"、"[详细信息]");定义( 'LNG_METHODCROSS_GSU_CLS' , 'class');定义('GSU_METH' , '方法');定义("CROSS_GSU_ACTION_NO_REMOVE","无法删除"模块"(已部署);

从给定的选定文件中检索常量名称和值的最可靠方法是什么。

编辑:

我需要将这些常量放入数组中,而无需直接通过读取文件来定义它们,例如:

array('LNG_GSU_LNK_LBL'=>'[details]','LNG_METHODCROSS_GSU_CLS'=> 'class')

。等

编辑2:到目前为止,我做到了这一点:

$file_array = file($path, FILE_SKIP_EMPTY_LINES);将 lang 文件内爆为删除 PHP 标签的字符串$string 1 = implode('', $file_array);$string 2 = str_replace(array(''), '', $string 1);正则表达式删除标记之间的内容$regex = '/''/''*.+?''*''//si';$replace_with = '';$replace_where = $string 2;$string 3 = preg_replace($regex, $replace_with, $replace_where);正则表达式:删除多个换行符$string 4 = preg_replace("/'+/", "'", $string 3);

编辑3:

预期成果

阵列 ("LNG_GSU_LNK_LBL" => "[详细信息]",'LNG_METHODCROSS_GSU_CLS' => '类',"GSU_METH" => "方法",'CROSS_GSU_ACTION_NO_REMOVE' => '无法删除 ''' 模块 '''(是);已部署');

如果你不想包含该文件,那么你应该使用:token_get_all()。

否则,您应该要求/包含包含它们的文件,并且可以迭代使用 get_defined_constants()

$all = array();
$consts = get_defined_constants();
foreach($consts as $k=>$v){
   if (strpos($k,"LNG")===0 && !isset($all[$k]))    
      $all[$k]=$v;
}

请注意,解析 php 源代码就像用正则表达式解析 HTML,最好避免使用它。

基于dynamic的答案,将该文件包含在另一个单独的,Web可访问的文件中,该文件未在当前应用程序中加载(因此在运行时将没有其他用户定义的常量):

//standalone.php
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
echo json_encode($newUserConsts);
//within your application
$newUserConsts = json_decode(file_get_contents('http://yoursite.com/standalone.php'));

或者,如果您无法创建单独的 Web 可访问文件:

$consts = get_defined_constants(true);
$existingUserConsts = $consts['user'];
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
var_dump(array_diff_key($newUserConsts, $existingUserConsts));