简体   繁体   中英

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');
// outputs 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 (eg, 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM