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


In PHP, How to call function in string?

说,字符串是:

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

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


如果你是打电话的方法的一些类,你可以使用正常的可变扩建。例如: P / < >

1
2
3
4
5
6
7
8
9
10
11
<?php
class thingie {

  public function sayHello() {
    return"hello";
  }

}

$t = new thingie();
echo"thingie says: {$t->sayHello()}";

这将输出: P / < >

thingie says: hello

注意,braces周围的召唤,是需要的。 P / < >


就用这个: P / < >

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

它将呼叫功能期间创作的字符串。 P / < >


1
2
3
4
5
6
7
$str="abcdefg foo() hijklmopqrst";
function foo() {return"bar";}

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

输出: P / < >

1
$replaced == 'abcdefg bar hijklmopqrst';

这将允许任何情况下世纪文学功能的名称。如果你需要的任何其他symbols,给他们的pattern,公元前[a-zA-Z_]。 P / < >

很小心,功能允许你去叫。你应该至少检查,如果美元米[ 1 ] contains的whitelisted功能到不允许remote代码attacks溶液注射。 P / < >

1
2
3
4
5
6
7
8
9
$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 C "abcdefg foo() bat() hijklmopqrst"outputs "abcdefg bar bat() hijklmopqrst"。 P / < >

optimisation为whitelisting进场(建筑pattern dynamically从allowed功能名称,公元前(foo|bar)。 P / < >

1
2
3
4
5
6
$allowedFunctions = array("foo","bar");

$replaced = preg_replace_callback("~(".implode("|",$allowedFunctions).")\(\)~",
     function ($m) {
          return $m[1]();
     }, $str);


1
2
3
4
5
6
function foo()
{
    return 'Hi';
}
$my_foo = 'foo';
echo"{$my_foo()}";


1
2
$foo = foo();
$str ="abcdefg {$foo} hijklmopqrst";


得到arbitrary expressions被evaluated从双上市的字符串,你可以在speculate可变-功能: P / < >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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 ) )}!";

结果: P / < >

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

references: P / < >

  • https:/ / / / / / functions.variable-functions.php EN secure.php.net手册
  • secure.php.net https:/ / / / / /它language.types.string.php # language.types.string.parsing手册


它仍然是不可能的,有hacks可用,但不是什么我会推荐而suggest粘到与老式的公元前$str="abcdefg". foo() ." hijklmopqrst";点算子 P / < >

每级的复杂(卷曲)语法文件 P / < >

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.