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

时间:2014-11-17 22:10:37

标签: php regex constants

最新编辑:
好吧,我提出了一个相当“可靠”的解决方案,以(便携式)功能的形式,但由于一些人在这里因为不理解问题并阻止了这个问题(一个军事解决方案:杀死你不明白的东西)而感到厌烦),我不能在这里发布。可惜。

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

define ('LNG_GSU_LNK_LBL',  '[details]');
define( 'LNG_METHODCROSS_GSU_CLS'   ,'class');
define('GSU_METH'  ,  'method');
define ( 'CROSS_GSU_ACTION_NO_REMOVE', 'cannot remove \' module \'(is); deployed');

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

编辑:

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

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

...等

编辑2: 到目前为止,我到目前为止:

$file_array = file($path, FILE_SKIP_EMPTY_LINES);

//implode lang file into a string removing php tags
$string1 = implode('', $file_array);
$string2 = str_replace(array(''), '', $string1);

//regex removing content between markers
$regex = '/\/\*.+?\*\//si';
$replace_with = '';
$replace_where = $string2;
$string3 = preg_replace($regex, $replace_with, $replace_where);

//regex: remove multiple newlines
$string4 = preg_replace("/\n+/", "\n", $string3);

编辑3:

预期结果

array (
'LNG_GSU_LNK_LBL' => '[details]',
'LNG_METHODCROSS_GSU_CLS' => 'class',
'GSU_METH' => 'method',
'CROSS_GSU_ACTION_NO_REMOVE' => 'cannot remove \' module \'(is); deployed'
);

2 个答案:

答案 0 :(得分:2)

如果您不想包含该文件,则应使用: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 with regex一样,更好的选择是避免它。

答案 1 :(得分:1)

基于动态的答案,将文件包含在另一个单独的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));