2012-01-31 2 views
1

다음은 시나리오입니다.Smarty 및 PHP 변수 작업

나는이처럼 보이는 DB에 텍스트를 가지고 : 당신이이 개 멋지 변수 {$name}{$index}

가 들어 볼 수있는 바와 같이 지금은 멋지와 변수에 값을 할당해야

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

. 스마티를 모르는 사람들을 위해, 값은 쉽게 길을 할당 할 수 있습니다 :

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

문제는이 텍스트를 DB에서오고, 나는 텍스트에있을 것이다 변수 모르는, 그래서이다 하고 추상적에 코드를 시도하고 다음

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는 정상적으로 실행하기 전에 변수를 그대로 인쇄합니다.

도와주세요.

+0

을 내가 ($ 일치) 평가 후면도 시도했지만 전혀 운. –

+1

멋지게 사용하지 마십시오. PHP는 이미 강력한 템플릿 엔진입니다. – dynamic

+0

좋은 조언. 하지만 지금은 전혀 도움이되지 않습니다. 나는 멋쟁이를 사용하고 있고 그것을 사용하는 솔루션이 필요합니다 ... –

답변

0

정규식 {(.+)}을 사용 중이라면 .+은 보이는 모든 것을 먹을 것이므로 $name} {$index과 일치합니다.

당신은 욕심이 살인자를 사용해야합니다 ''/\\{(.+?)\\}/U''

+0

당신은 어떤 특별한 이유라도 \\ – dynamic

+0

doulbe해서는 안됩니다? 나는'\ d'와 같이'DEL' 문자로 해석 될 수있는 미래의 특별한 의미를 가지기 때문에 주로 문자와 숫자와 함께 좋은 습관으로 생각했습니다. – Vyktor

3

이 교체 :이

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

:

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

IT WORKED !!!!!! –

+0

왜? 문제는 무엇 이었습니까? 나는 호기심이다 –

+0

'eval'은 다른 변수 이름을 기반으로 변수를로드하는 올바른 방법이 아닙니다. '$ {...} '은 길입니다. "..."는 보간법이있는 문자열과 같아서 거기에 다른 변수를 넣을 수 있습니다. –