dqf42223 2012-06-30 21:22
浏览 27

用正则表达式解析php函数[关闭]

I'm trying to parse a function in php to 3 things: name, arguments and content.

I have a regex that do that good, but the problem is the he can parse only one function. i.e - if i wrote a function he can parse it, but if i wrote a function and a print_r he will mixed up.

The regex is this:

preg_match("/function.+?([a-zA-Z0-9_]+?)[\s]*\((.*?)\)[\s]*\{(.+)\}/is", $code, $functions);

I didn't wrote it, someone helped me becuase i'm suck in regex. Thank you for help.

Best regards, Roy.

  • 写回答

1条回答 默认 最新

  • dongxi7609 2012-06-30 21:47
    关注

    I'm not sure i understand your problem, but it seems to be that your regex won't parse multiple functions from the $code variable?

    Here is a slightly re-written regexp that can handle multiple functions

    $code = 'function myfunc1() { echo "This is myfunc1"; } function myfunc2($arg1 = array(), $arg2) { echo "This is myfunc2"; print_r($arg1); }';
    
    preg_match_all("/function\s*([a-zA-Z0-9_]+)\s*\((.*)\)\s*\{(.*)\}/Uis", $code, $functions);
    
    echo '<pre>';
    print_r($functions);
    echo '</pre>';
    

    And the output

    Array
    (
        [0] => Array
            (
                [0] => function myfunc1() { echo "This is myfunc1"; }
                [1] => function myfunc2($arg1 = array(), $arg2) { echo "This is myfunc2"; print_r($arg1); }
            )
    
        [1] => Array
            (
                [0] => myfunc1
                [1] => myfunc2
            )
    
        [2] => Array
            (
                [0] => 
                [1] => $arg1 = array(), $arg2
            )
    
        [3] => Array
            (
                [0] =>  echo "This is myfunc1"; 
                [1] =>  echo "This is myfunc2"; print_r($arg1); 
            )
    
    )
    

    This will however run into problems if your function bodies contain the { } characters. I don't think that can be handled by a single regular expression.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题