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 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件