Search code examples
phpcallbackpreg-replace-callback

preg_replace_callback: passing in replacement callback as a variable not working


This does not work

        $check["pattern"] = "/correct/";
    $callback = "function ($m) { return ucfirst($m[0]);}";
    echo preg_replace_callback($check["pattern"],$callback,"correct" );

output: correct

This works

        $check["pattern"] = "/correct/";
    echo preg_replace_callback($check["pattern"],function ($m) { return ucfirst($m[0]);},"correct" );

output: Correct

Why, and how to make it work with the function stored inside a var? :)


Solution

  • Why would you want to do that? I see no reason to store the function inside a variable, to be honest. Nevertheless, if you really want to do this, take a look at create_function:

    <?php
    $check["pattern"] = "/correct/";
    $callback = create_function('$m', 'return ucfirst($m[0]);');
    echo preg_replace_callback( $check['pattern'], $callback, "correct" );
    
    // Output: "Correct"