What is wrong with this PHP function
I am new to PHP
and regular expression. I was going thorugh some online examples and came with this example:
<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outpu开发者_StackOverflow中文版ts helloWorld
?>
in php.net
but to my surprise it does not work and keep getting error:
PHP Parse error: parse error, unexpected T_FUNCTION
Why get error ?
You are using PHP's Anonymous functions: functions that have no name.
When I run your program I get no error. May be you are trying it on a PHP < 5.3
.
Anonymous functions are available since PHP 5.3.0.
If PHP
version is creating the problem you can re-write the program to not use Anonymous functions as:
<?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]);
}
?>
This example is for PHP 5.3. You probably use something older (e.g., PHP 5.2).
Try this instead:
<?php
function callback($match) {
return strtoupper($match[1]);
}
echo preg_replace_callback('~-([a-z])~', 'callback', 'hello-world');
Are you using a version prior to PHP 5.3.0? Anonymous functions are not supported in versions prior to that one.
You can check your version with a phpinfo page.
This should work on pre-5.3 versions:
echo preg_replace_callback(
'/-([a-z])/',
create_function( '$arg', 'return strtoupper($arg[1]);' ),
'hello-world'
);
Regards
rbo
精彩评论