preg_replace, preg_replace_callback and Array to string conversion

1.1k views Asked by At

I have this code from an app in PHP 5.4 :

$rightKey = preg_replace(array(
                "/(_)(\p{L}{1})/eu",
                "/(^\p{Ll}{1})/eu"
            ), array(
                "mb_strtoupper('\\2', 'UTF-8')",
                "mb_strtoupper('\\1', 'UTF-8')"
            ), $key);

It didn't work well, because preg_replace is deprecated. I did some researches and turned it into :

$rightKey = preg_replace_callback(array(
                "/(_)(\p{L}{1})/u",
                "/(^\p{Ll}{1})/u"
            ), function($m) { return array(
                "mb_strtoupper('\\2', 'UTF-8')",
                "mb_strtoupper('\\1', 'UTF-8')"
            ); }, $key);

I changed the function to preg_replace_callback, I removed the "e", and I added a callback.

But now I have :

Array to string conversion

And, I really don't know how to adapt the callback so it works ^^.

Thanks :),

1

There are 1 answers

0
Toto On

The function must return a string, not an array, it is the same function for every matches:

$key = 'abc _def';
$rightKey = preg_replace_callback(array(
            "/_(\p{L})/u",
            "/(^\p{Ll})/u"
        ), 
        function($m) { 
            return mb_strtoupper($m[1], 'UTF-8');
        },
        $key);
echo $rightKey;

Output:

Abc Def