dongshenchi5364 2013-06-25 08:02
浏览 50
已采纳

正则表达式从php文件中获取特定的函数代码

I'm editing a PHP file to replace a function's code by another code provided. My problem is that the function's code may change. So, I don't know exactly how I should do the regex to find it.

Here's an example:

function lol()
{
    echo('omg');
    $num=0;
    while($num<100)
    {
        echo('ok');
    }
}
function teste()
{
    echo('ola');
    while($num<100)
    {
        echo('ok');
    }
}
function test()
{
    echo('oi');
    while($num<100)
    {
        echo('ok');
    }
}

What I need is to get the code of function teste(), which would be:

echo('ola');
while($num<100)
{
    echo('ok');
}

BUT: I do not know how many whiles, foreaches or how many brackets are inside the functions, neither I don't know it's order. The example was just an example.

How would I be able to get the function's code? Thank you in advance.

  • 写回答

2条回答 默认 最新

  • drrog9853 2013-06-25 08:27
    关注

    Disclaimer

    As other users stated, this is probably not a good approach. And if you decided to use it anyway, double-check your result as regex can be treacherous.

    Ugly solution

    You can you something like to match even if the function is the last one (@Nippey):

    (?:function teste\(\))[^{]*{(.*?)}[^}]*?(?:function|\Z) 
    

    Note: I'm using (?:xyz) which is for non-capturing parentheses group. Check if your regex engine support it.

    Output

        echo('ola');
        while($num<100)
        {
            echo('ok');
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教