2012-09-23 37 views
0

我有这个字符串替换[陷]用HTML代码或PHP代码

$s = 'Yo be [diggin = array("fruit"=> "apple")] scriptzors!'; 

然后把它通过

$matches = null; 
preg_match_all('/\[(.*?)\]/', $s, $matches); 
var_dump($matches[1]); 

检查,但我想它做的事情是下面的,它应该返回以下

print "yo be"; 
$this->diggin(SEND ARRAY HERE); 
print "scriptzors!"; 

EDIT显示问题下面的答案

$s = 'Yo be [diggin = array("fruit"=>"apple")] scriptzors!'; 
$matches = null; 
preg_match_all('/\[(.*?)\]/', $s, $matches); 

$var = explode(' = ', $matches[1]); 
print $var[0]; //THIS DOES NOT PRINT 
+0

返回部分对我来说很陌生。你的$ s字符串应该转换成什么? –

+0

它的正文,来自我们的数据库,并且我想让我们的工作人员在一个网站的内容中使用插件或运行功能。 想像wordpress – RussellHarrower

+0

这是什么“$ this-> diggin(SEND ARRAY HERE);”做?转换后的输出结果如何? –

回答

0

你真的很接近。您可以explode=的字符串,但在=周围包含空格。然后第一个元素是函数名称,在这种情况下是diggin,第二个元素是数组,但是是一个字符串。你需要eval那个,以便它将是一个适当的数组数据类型。

$var = explode(' = ', $matches[1][0]); 
call_user_func_array(array($this, $var[0]), eval($var[1] . ';')); 
// or do 
$this->{var[0]}(eval($val[1] . ';')); 

作为替代方案,你也可以修改正则表达式,让你不用调用explode做。

preg_match_all('/\[([a-z0-9_]*)\s*?=\s*(.*)\]/i', $s, $matches); 

无论哪种方式,你要确保你消毒用户输入,因为eval可以evil

+0

我可以问我该如何将它放在正确的部分?该函数将函数转换为函数,但如何分割$ s中的内容,以便将函数插入到{}为 – RussellHarrower

+0

的位置。您应该为在您找到的每个“函数调用”中分割“$ s”的内容字符串。当你拥有了所有的东西(即所有的函数都被调用)之后,就构成了你之前分割的字符串。 –

+0

由于某种原因,它没有得到$ var [0] – RussellHarrower

0

这将调用该函数而不使用eval并将自己暴露给代码注入。

preg_match_all('/\[([a-z0-9_]*)\s*?=\s*array\((.*)*\)\]/i', $s, $matches); 
$var = explode(',', $matches[2][0]); 
$result = array(); 
foreach ($var as $value) { 
    $keyvaluepair = explode('=>', $value); 
    $result[$keyvaluepair[0]] = $keyvaluepair[1]; 
} 
$this->{var[0]}($result);