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

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

4 Comments

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...
It, indeed, it insecure, but as long as you have control over what happens, I guess using create_function would work.
@giorgio79 Just tested the code. It correctly outputs "Correct".
Yep, thanks. Stackoverflow makes me wait 10 mintues to accept the answer.
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.

1 Comment

Thanks, this is a correct answer as well. Berry also gave me a working copy and paste solution, so will accept that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.