2011-02-15 55 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;