簡體   English   中英

使用Smarty和PHP變量

[英]Working with Smarty and PHP variables

這是場景。

我在數據庫中有如下文字:

blah blah blah blah blah {$name} {$index}

如您所見,它包含兩個Smarty變量{$name}{$index}

現在,我需要使用Smarty將值分配給變量。 對於不了解Smarty的用戶,可以通過以下方式輕松分配值:

$smarty->assign('name_of_the_variable', $variable);

問題在於該文本來自數據庫,並且我不知道文本中將包含哪些變量,因此我嘗試通過以下操作來抽象代碼:

    function getPageContent($page) {

        $smarty = new Smarty(); // initializing Smarty

    //selecting the content and saving it into the $content variable
        $q='SELECT * FROM pages_blocks WHERE Page="'.$page.'"';
         $r=mysql_query($q) or die(mysql_error());
             while($row = mysql_fetch_array($r)) {
              $content = $row['Content'];
               }

//defining variables
        $name = "NAME";
        $index = "INDEX";

    //getting all the variables inside brackets {}
               preg_match_all('/{(.+)}/U', $content, $matches);


    //abstracting the code assigning values to the variables found   
        foreach ($matches[1] as $match) {
         $foo = str_replace('$', '', $match); //removing the $ to give a name to smarty
          $smarty->assign(''.$foo.'', $match); //final assignation of name and its variable
         }
           $smarty->display('string:'.$content); //displaying the final content
        }

問題在於最終內容如下所示:

blah blah blah blah blah $name $index

代替

blah blah blah blah blah NAME INDEX

出了點問題。 Smarty正在按原樣打印變量,而不是像往常一樣先運行它們。

請幫我。

替換為:

$smarty->assign(''.$foo.'', $match);

有了這個:

$smarty->assign(''.$foo.'', ${$foo});

您使用的是regexp {(.+)}.+會“吃掉”它看到的所有內容,因此它將匹配: $name} {$index

您應該使用貪婪的殺手: ''/\\\\{(.+?)\\\\}/U''

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM