如果你正在构建语法树,你应该写解析器是没有问题的。但是如果您只需要解析此示例,则regex仍然可能是一个工具:
$str = 'all, ("hi there", (these, that) , other), another';
$str = preg_replace('/\, /', ',', $str); //get rid off extra spaces
/*
* get rid off undefined constants with surrounding them with quotes
*/
$str = preg_replace('/(\w+),/', '\'$1\',', $str);
$str = preg_replace('/(\w+)\)/', '\'$1\')', $str);
$str = preg_replace('/,(\w+)/', ',\'$1\'', $str);
$str = str_replace('(', 'array(', $str);
$str = 'array('.$str.');';
echo '
';
eval('$res = '.$str); //eval is evil.
print_r($res); //print the result
注意:如果输入格式不正确,正则表达式肯定会失败。我正在写这个解决方案,只是在你需要快速脚本的情况下。编写词法分析器和解析器是耗时的工作,需要大量的研究。