In PHP, How to call function in string?

前端 未结 7 1938
误落风尘
误落风尘 2020-12-10 04:42

say,string is:

$str=\"abcdefg foo() hijklmopqrst\";

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

7条回答
  •  無奈伤痛
    2020-12-10 05:12

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

提交回复
热议问题