2010-04-28 104 views
1

我是PHP和正则表达式的新手。我正想thorugh一些网上的例子,来到这个例子:这个PHP函数有什么问题

<?php 
echo preg_replace_callback('~-([a-z])~', function ($match) { 
    return strtoupper($match[1]); 
}, 'hello-world'); 
// outputs helloWorld 
?> 

php.net但让我吃惊不工作,并不断收到错误:

PHP Parse error: parse error, unexpected T_FUNCTION 

为什么出现错误?

+1

的PHP版本,你运行这个吗? – codaddict 2010-04-28 12:46:08

+0

5.2.1在Windows上的版本。 – user325894 2010-04-28 12:51:10

回答

6

您正在使用PHP的Anonymous functions:函数有没有名称

当我运行你的程序时,我得到没有错误。可能是你正在尝试一个PHP < 5.3

匿名函数自PHP 5.3.0起可用。

如果PHP版本创建的问题,你可以在程序重新编写到不使用匿名函数为:

<?php 

// a callback function called in place of anonymous function. 
echo preg_replace_callback('~-([a-z])~','fun', 'hello-world'); 

// the call back function. 
function fun($match) { 
    return strtoupper($match[1]); 
} 

?> 
+0

您的新程序有效。谢谢。 – user325894 2010-04-28 12:51:53

+0

@unicornaddict:在这种特殊情况下,'preg_replace_callback'的第二个参数应该是一个字符串。 – salathe 2010-04-28 13:12:03

+0

@salathe:感谢指点。有趣的是,即使没有引用在这里通知:)。看起来OP也没有看到通知:) – codaddict 2010-04-28 13:15:51

2

这个例子是PHP 5.3。您可能会使用较旧的东西(例如PHP 5.2)。

试试这个:

<?php 
function callback($match) { 
    return strtoupper($match[1]); 
} 
echo preg_replace_callback('~-([a-z])~', 'callback', 'hello-world'); 
1

这应该预先5.3版本的工作:

echo preg_replace_callback(
     '/-([a-z])/',  
     create_function('$arg', 'return strtoupper($arg[1]);'), 
     'hello-world' 
    ); 

问候

RBO