2011-02-15 143 views
0

我有这些代码:这个preg_replace命令有什么问题?

$string = 'Hello [*tt();*], how are you today?'; 
preg_match("/\[\*(.*?)\*\]/",$string,$match); 
$func = $match[1]; 
$d = eval($func); 
$newstring = preg_replace("/\[\*(.*?)\*\]/",$d,$string); 
echo $newstring; 

function tt() { 
    return 'test'; 
} 

我想他们是从他们达到我的意思。我想替换tt();与其output.I预计它的工作,但tt();无(空字符串)替换。

回答

3

从PHP文档:http://au2.php.net/manual/en/function.eval.php

的eval()返回,除非被称为在所评估的代码返回NULL,在这种情况下,被返回传递给返回值。

$d = eval("return $func"); 

eval应谨慎使用。见When is eval evil in php?

+0

哇,谢谢。为什么是eval坏?因为它可以运行一个文本为php代码?我认为当文本从用户获取时使用eval是不好的,但在我的情况下,文本是由管理员直接在数据库中定义的。 – 2011-02-15 07:10:27

+0

更新我的回答,比“eval是坏”更多的信息:D – Jacob 2011-02-15 07:19:12

+0

谢谢雅各布;) – 2011-02-15 07:59:39

1

$d = eval($func);

应该

eval('$d = ' . $func);

1

你的正则表达式的罚款。您的问题与eval()声明有关。它不会像您期望的那样返回一个值。作业也需要在eval()中进行。

function tt() { 
    return 'test'; 
} 

$string = 'Hello [*tt();*], how are you today?'; 
preg_match("/\[\*(.*?)\*\]/",$string,$match); 
$func = $match[1]; 
eval('$d = ' . $func); 
$newstring = preg_replace("/\[\*(.*?)\*\]/",$d,$string); 
echo $newstring;