0

I want to do something like this:

I have this string:

Lorem ipsum {shortcode 42} dolor sit amet.

I want to parse it like this:

preg_replace('/\{shortcode (\d+)\}/i', MyClass::myFunction('$1') , $content);

The MyClass code looks like this:

class MyClass {
    public static function myFunction(string $id) {
        // ...

        return 'hello world';
    }

}

But in the myFunction() the $id will always the $1 string, and not the content of the original $1, what is a number.

How can I pass the preg_replace replacement value in parameter to my function?

4
  • 2
  • “But in the myFunction() the $id will always the $1 string” - not only that, it will be called before any replacing even happens. If you specify a function call as parameter of another function, then that function call happens before the other function even runs.
    – CBroe
    Mar 2, 2021 at 14:25
  • I checked this too, but same result. Could you present me an example with my code? I think this is a too simple thing, but I don't see something basic thing... Thanks!
    – netdjw
    Mar 2, 2021 at 14:26
  • There are multiple examples on that manual page.
    – CBroe
    Mar 2, 2021 at 14:27

2 Answers 2

2

Without rewriting your class method, use an anonymous function in preg_replace_callback to call your method using index 1 as the first capture group match:

$result = preg_replace_callback('/\{shortcode (\d+)\}/i',
                                function($m) {
                                    return MyClass::myFunction($m[1]);
                                }, $content);

Or you can call the static method, but then you would need to use the 1 index of the argument there:

// ['MyClass', 'myFunction'] or 'MyClass::myFunction'
$result = preg_replace('/\{shortcode (\d+)\}/i', ['MyClass', 'myFunction'], $content);

class MyClass {
    public static function myFunction(array $array) {
        // use $array[1]

        return 'hello world';
    }

}
0

Simple example with static method of class as a callback:

class MyClass {
    static function myFunction($arg) {
        return "[Hello, {$arg[1]}]";
    }
}

$content = 'Lorem ipsum {shortcode 42} dolor sit amet.';
echo preg_replace_callback('/\{shortcode (\d+)\}/i', 'MyClass::myFunction', $content);

Fiddle.

Not the answer you're looking for? Browse other questions tagged or ask your own question.