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);

但在空格或','时不起作用......

我怎样才能让它一直工作?

4

2 回答 2

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

要至少使前两个工作,您应该使用token_get_all根据PHP 解析规则解析PHP 文件,然后遍历生成的令牌并提取您需要的值。
为了使所有情况都能正常工作,您需要实际评估PHP 代码,即include文件,然后简单地访问常量作为 PHP 中的常量。

于 2012-06-25T07:42:49.623 回答
1

您应该get_defined_constants()为此使用功能。它返回一个关联数组,其中包含所有常量的名称及其值。

于 2012-06-25T10:19:22.423 回答