在PHP中,如何在字符串中调用函数?

问题描述:

例如,字符串为:

$str="abcdefg foo() hijklmopqrst";

如何让php调用foo()并将返回字符串插入此字符串?

How to let php call foo() and insert the return string to this string?

$str="abcdefg foo() hijklmopqrst";
function foo() {return "bar";}

$replaced = preg_replace_callback("~([a-z]+)\(\)~", 
     function ($m){
          return $m[1]();
     }, $str);

输出:

$replaced == 'abcdefg bar hijklmopqrst';

这将允许任何小写字母作为函数名称.如果需要其他符号,请将其添加到模式中,即[a-zA-Z_].

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_].

非常小心允许您调用的函数.您至少应检查$ m [1]是否包含列入白名单的函数,以禁止远程代码注入攻击.

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);

"abcdefg foo() bat() hijklmopqrst"上的Testrun输出"abcdefg bar bat() hijklmopqrst".

Testrun on "abcdefg foo() bat() hijklmopqrst" outputs "abcdefg bar bat() hijklmopqrst".

白名单方法的优化(从允许的函数名称即(foo|bar)动态构建模式.

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);