views:

139

answers:

4

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 ?

+1  A: 

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.

MiffTheFox
+6  A: 

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

?>
codaddict
your new program works. Thanks.
@unicornaddict: the second argument to `preg_replace_callback` should be a string in this particular case.
salathe
@salathe: Thanks for pointing. Interestingly even not quoting worked here with a Notice :). Looks like OP also did not see the Notice :)
codaddict
+2  A: 

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');
binaryLV
A: 

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

rubber boots