How do I access a variable inside of preg_replace_callback?

✔ Recommended Answer

As your callback function is a closure, you can pass extra arguments via use

function ($match) use ($kvPairs) {    ...}

better than polluting the global space


Answered By: Mark Baker

Method #2

To access a variable inside preg_replace_callback, you need to use the use keyword to import the variable into the callback function's scope. Here's an example:

$my_variable = "Hello, World!"; $string = "Replace this: %s"; $new_string = preg_replace_callback("/%s/", function($matches) use ($my_variable) { return $my_variable; }, $string); echo $new_string; // Output: Replace this: Hello, World!

In this example, the use ($my_variable) statement imports the $my_variable variable into the callback function's scope, allowing it to be accessed and used inside the function.

You can import multiple variables by separating them with commas in the use statement. Note that the variables you import must be defined outside the scope of the callback function.


Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755