In PHP, How to call function in string?

前端 未结 7 1936
误落风尘
误落风尘 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:03

    Just use this:

    $str = "abcdefg".foo()."hijklmnopqrstuvwxyz";
    

    It will call function during string creation.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-10 05:12
    $foo = foo();
    $str = "abcdefg {$foo} hijklmopqrst";
    
    0 讨论(0)
  • 2020-12-10 05:14

    To get arbitrary expressions being evaluated from a double-quoted string you can speculate on variable-functions:

    <?php
    // A user function
    function foo() {
        return 'bar';
    }
    
    /**
     * The hack
     *
     * @param $v mixed Value
     * return mixed Value (untouched)
     */
    $_ = function ( $v ) {
        return $v;
    };
    
    // Happy hacking
    echo "Foo is {$_( foo() )} and the sum is {$_( 41 + 1 )}...{$_( str_repeat( ' arrh', 3 ) )}!";
    

    Result:

    Foo is bar and the sum is 42... arrrh arrrh arrrh!
    

    References:

    • https://secure.php.net/manual/en/functions.variable-functions.php
    • https://secure.php.net/manual/it/language.types.string.php#language.types.string.parsing
    0 讨论(0)
  • 2020-12-10 05:14

    Its still not possible, There are hacks available but not what I would recommend rather suggest to stick with old school dot operator i.e. $str="abcdefg ". foo() ." hijklmopqrst";

    As per the Complex (curly) syntax documentation

    Note:
    Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

    0 讨论(0)
  • 2020-12-10 05:21

    If you're calling a method of some class, you can use normal variable expansion. For example:

    <?php
    class thingie {
    
      public function sayHello() {
        return "hello";
      }
    
    }
    
    $t = new thingie();
    echo "thingie says: {$t->sayHello()}";
    

    This will output:

    thingie says: hello

    Note that the braces around the call are required.

    0 讨论(0)
提交回复
热议问题