正则表达式从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.

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');
    }

Using recursive pattern (?R) you can match nested brackets:

$result = preg_replace_callback('#(.*?)\{((?:[^{}]|(?R))*)\}|.*#si', function($m){
    if(isset($m[1], $m[2]) && preg_match('#function\s+teste\b#i', $m[1])){
        return $m[2];
    }
}, $code); // Anonymous function is used here which means PHP 5.3 is required

echo $result;

Online demo