2012-06-02 59 views
8

我將我的頁面內容保存在數據庫中,並希望在字符串中執行任何PHP代碼。所以,如果我的字符串是:在字符串中執行PHP代碼

<h1>Welcome</h1><?php echo $motto?><br/> 

我只是想執行echo $motto。使用eval()將嘗試執行<h1>Welcome</h1>

任何方式來做到這一點?

+1

是不斷呈現和邏輯獨立。必須這樣做才能表明您可能想要重新考慮您的設計選擇。 – dm03514

+0

對於您構建網站的方式,我現在可以告訴您這會導致問題。以下是我的建議:使用Smarty或類似軟件來分離模板和代碼。 – Hassan

+0

這看起來像你已經做出了一個非常糟糕的設計決定。 – PeeHaa

回答

16

Needles說你應該儘快找到另一種解決方案。在此期間,你可以使用eval這樣的代碼:

$str = '<h1>Welcome</h1><?php echo $motto?><br/>'; // Your DB content 

eval("?> $str <?php "); 

演示:http://codepad.org/ao2PPHN7

我不能強調足夠:EVAL是危險的,而應用程序代碼不應該在數據庫中。嘗試模板解析器,如Smarty,Dwoo或我的最愛:Twig

+2

...或簡單的'eval(「?> $ str」);'你只需跳出PHP塊。 –

2

真的不應該這樣做,但是,如果你絕對要,你可以使用這個類做:

class PhpStringParser 
{ 
    protected $variables; 

    public function __construct($variables = array()) 
    { 
     $this->variables = $variables; 
    } 

    protected function eval_block($matches) 
    { 
     if(is_array($this->variables) && count($this->variables)) 
     { 
      foreach($this->variables as $var_name => $var_value) 
      { 
       $$var_name = $var_value; 
      } 
     } 

     $eval_end = ''; 

     if($matches[1] == '<?=' || $matches[1] == '<?php=') 
     { 
      if($matches[2][count($matches[2]-1)] !== ';') 
      { 
       $eval_end = ';'; 
      } 
     } 

     $return_block = ''; 

     eval('$return_block = ' . $matches[2] . $eval_end); 

     return $return_block; 
    } 

    public function parse($string) 
    { 
     return preg_replace_callback('/(\<\?=|\<\?php=|\<\?php)(.*?)\?\>/', array(&$this, 'eval_block'), $string); 
    } 
} 

這樣稱呼它:

$p = new PhpStringParser(); 
echo $p->parse($string); 

來源:http://www.php.net/manual/en/function.eval.php#108091

+0

將主體保存在數據庫中的原因是,客戶端可以在我製作的自定義Windows程序中對其進行編輯。我試圖以不同的方式進行設置,但同時該網站需要像這樣上網。 – bmandesign

+1

與ob_start(); eval(「?> $ str」); $ result = ob_get_clean();'相比,上面有什麼好處? – goat

0

要使用內使用可變呼應字符串:

echo "<h1>Welcome</h1>$motto<br/>" 

甚至:

echo sprintf('<h1>Welcome</h1>%s<br/>', $motto) 

這裏是一個演示http://codepad.org/f6aALD6w