【问题标题】:How can I get constant name and constant value in file如何在文件中获取常量名称和常量值
【发布时间】:2012-06-25 07:06:11
【问题描述】:

我有带有文本和常量的文件。如何获取常量名称和常量值。问题是常量值有一些时间空间。我使用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);

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

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

【问题讨论】:

  • 为什么不能简单地include 文件并将常量用作常量?

标签: php


【解决方案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 中的常量。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2010-12-25
      • 2016-02-02
      • 2011-02-20
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多