Regex to parse define() contents, possible?

前端 未结 5 1930
北海茫月
北海茫月 2021-01-13 11:06

I am very new to regex, and this is way too advanced for me. So I am asking the experts over here.

Problem I would like to retrieve the constants /

5条回答
  •  时光取名叫无心
    2021-01-13 11:27

    Try this regular expression to find the define calls:

     /\bdefine\(\s*("(?:[^"\\]+|\\(?:\\\\)*.)*"|'(?:[^'\\]+|\\(?:\\\\)*.)*')\s*,\s*("(?:[^"\\]+|\\(?:\\\\)*.)*"|'(?:[^'\\]+|\\(?:\\\\)*.)*')\s*\);/is
    

    So:

    $pattern = '/\\bdefine\\(\\s*("(?:[^"\\\\]+|\\\\(?:\\\\\\\\)*.)*"|\'(?:[^\'\\\\]+|\\\\(?:\\\\\\\\)*.)*\')\\s*,\\s*("(?:[^"\\\\]+|\\\\(?:\\\\\\\\)*.)*"|\'(?:[^\'\\\\]+|\\\\(?:\\\\\\\\)*.)*\')\\s*\\);/is';
    $str = '';
    preg_match_all($pattern, $str, $matches, PREG_SET_ORDER);
    var_dump($matches);
    

    I know that eval is evil. But that’s the best way to evaluate the string expressions:

    $constants = array();
    foreach ($matches as $match) {
        eval('$constants['.$match[1].'] = '.$match[1].';');
    }
    var_dump($constants);
    

提交回复
热议问题