0

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? :)

giorgio79
  • 3,787
  • 9
  • 53
  • 85

2 Answers2

1

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"
Berry Langerak
  • 18,561
  • 4
  • 45
  • 58
  • I am letting my developer users submit preg_replace_callback functions in a hosted solution in a text field :) Yes I know it is not the most secure, but they go through an approval phase. I think this is faster than letting them submit code in github, and I hate mile long php files with hundreds of lines. Database to the rescue... – giorgio79 Sep 13 '12 at 09:22
  • 1
    It, indeed, it insecure, but as long as you have control over what happens, I guess using create_function would work. – Berry Langerak Sep 13 '12 at 09:24
  • 1
    @giorgio79 Just tested the code. It correctly outputs "Correct". – Berry Langerak Sep 13 '12 at 09:26
  • Yep, thanks. Stackoverflow makes me wait 10 mintues to accept the answer. – giorgio79 Sep 13 '12 at 09:27
1

If you do a var_dump on $callback = "function ($m) { return ucfirst($m[0]);}"; the result is a string. In the working situation you pass a Closure (anonymous function) as callback.

The manual is clear: a Closure is allowed, if you pass a string, it must be the name of a function.

JvdBerg
  • 21,777
  • 8
  • 38
  • 55
  • Thanks, this is a correct answer as well. Berry also gave me a working copy and paste solution, so will accept that. – giorgio79 Sep 13 '12 at 09:28