senzacionale
senzacionale

Reputation: 20936

How can I get constant name and constant value in file

I have files with texts an constants. How can I get constant name and constant value. Problem is that constant value has sometime spaces. I read files with file() and then with foreach...

Example:

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

I already tried:

to get constant name:

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

to get constant value

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

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

but not working when is space or ','...

How can i make this always working??

Upvotes: 0

Views: 384

Answers (2)

deceze
deceze

Reputation: 522636

A regular expression matching this would be this:

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

See http://rubular.com/r/m9plE2qQeT.

However, that only works if the strings are single quoted ', don't contain escaped quotes, the strings are not concatenated etc. For example, this would break:

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

To make at least the first two work, you should use token_get_all to parse the PHP file according to PHP parsing rules, then go through the resulting tokens and extract the values you need.
To make all cases work, you need to actually evaluate the PHP code, i.e. include the file and then simply access the constants as constants in PHP.

Upvotes: 1

lisachenko
lisachenko

Reputation: 6092

You should use get_defined_constants() function for that. It returns an associative array with the names of all the constants and their values.

Upvotes: 1

Related Questions