In PHP, How to call a function interpolated in string?
php
Solution
$str="abcdefg foo() hijklmopqrst";
function foo() {return "bar";}
$replaced = preg_replace_callback("~([a-z]+)\(\)~",
function ($m){
return $m[1]();
}, $str);
output:
$replaced == 'abcdefg bar hijklmopqrst';
This will allow any lower-case letters as function name. If you need any other symbols, add them to the pattern, i.e. `[a-zA-Z_]`.
Be VERY careful which functions you allow to be called. You should at least check if $m[1] contains a whitelisted function to not allow remote code injection attacks.
$allowedFunctions = array("foo", "bar" /*, ...*/);
$replaced = preg_replace_callback("~([a-z]+)\(\)~",
function ($m) use ($allowedFunctions) {
if (!in_array($m[1], $allowedFunctions))
return $m[0]; // Don't replace and maybe add some errors.
return $m[1]();
}, $str);
Testrun on `"abcdefg foo() bat() hijklmopqrst"` outputs `"abcdefg bar bat() hijklmopqrst"`.
Optimisation for whitelisting approach (building pattern dynamically from allowed function names, i.e. `(foo|bar)`.
$allowedFunctions = array("foo", "bar");
$replaced = preg_replace_callback("~(".implode("|",$allowedFunctions).")\(\)~",
function ($m) {
return $m[1]();
}, $str);
Problem
Let's say my string is: ``` $str = "abcdefg foo() hijklmopqrst"; ``` How do I let PHP call the function `foo()` and insert the returning string to the rest of that string?