在字符串中隔离数组变量的值


Isolating the value of an array variable in a string

假设我在php文件中有一行:

$config['fw_ls'] = 'some value';

我想得到引号之间的值。我试过的是像这样的组合

preg_match('/'$config'[''fw_ls'''] = ''([^''])*'';/',$sData,$aK);
var_dump($aK);

遗憾的是,我似乎无法获得引号之间的值,在上面的例子中,它返回了字符"t"。我真的不明白我做错了什么。我希望正则表达式从引号开始搜索,并获取所有内容,直到找到另一个引号。但这似乎并不完全正确。

如有任何帮助,我们将不胜感激。

试试这个:

$text = "'$config['fw_ls'] = 'some value';";
preg_match("#'''$config'['fw_ls'']'s*='s*'([^']+)';#", $text, $match);
print_r($match);
Array
(
    [0] => $config['fw_ls'] = 'some value';
    [1] => some value
)

您可能想要使用解析器,然后获得数组索引值之类的东西。以下是一个开源php解析器(在php中)的示例:

https://github.com/nikic/PHP-Parser

正则表达式不是解析器,因此很难根据您的问题判断您是否试图解析任意的php行,或者这是正则表达式可能是您的朋友的特殊情况。