2012-12-11 3 views
0

HTML 템플릿PHP에서 이와 같은 템플릿을 구문 분석하는 효율적인 방법은 무엇입니까?

<b><!--{NAME}--></b> 
... 
.. 
.. 
<b><!--{ADDRESS}--></b> 

PHP의 배열

array('name'=>'my full name', ..... , 'address'=>'some address '); 

내가 템플릿 파일을 많이 가지고 있고 그들 각각을 분석하고 연관 배열에에게없는 str_replace 주어진 데이터를 대체해야합니다.

정적 기능 ParseTemplate 코드의 현재 버전 ($ 데이터, $ 템플릿) {

:

나는

편집 도움이 될 수있는이 과정 또는 기타 기술/도구를 개선하기 위해 귀하의 제안이 필요

$html=$read==true ? self::GetCached($template,true) : $template ; foreach($data as $key=>$value){ if(is_array($value)){ foreach($data[$key] as $aval) $html = str_replace("<!--{".$key."}-->",$aval,$html); } else $html = str_replace("<!--{".$key."}-->",$value,$html); } return $html; 

}

감사

성능이 중요한 경우

foreach ($array as $key => $value) { 
    $html = str_replace("<!--{$key}-->", $value, $html) 
} 

이는 HTML에 strpos를 사용하고 가서 더 좋을 수 있습니다

+2

여기, 템플릿 엔진과 같은 Mustache를 사용하지 않는 이유 : //github.com/bobthecow/mustache.php#readme –

+0

@tuxtimo, plz 편집을 확인 – sakhunzai

+0

@JonathandeM. 당신의 제안에 감사드립니다 :) 그들은 유망한 것으로 보입니다 – sakhunzai

답변

1

PHP는 HTTPS 여기, 같은 http://mustache.github.com/#demo 같은 템플릿 엔진을 사용하지 않는 이유 PHP version

1

배열의 키는 항상 괄호 안에 템플릿 단어 같은 경우이런 식으로 뭔가를 할 자리 표시 자 하나씩. 큰 문자열에서 여러 번 str_replace를 수행하는 것이 더 빠를 것입니다. 성능에 문제가 없다면 반드시 필요한 것은 아닙니다.

편집 :

$index = strpos($html, "<!--"); 
while ($index !== false) { 
    // get the position of the end of the placeholder 
    $closing_index = strpos($html, "}-->", $index); 

    // extract the placeholder, which is the key in the array 
    $key = substr ($html, $index + 5, $closing_index); 

    // slice the html. the substr up to the placeholder + the value in the array 
    // + the substr after 
    $html = substr ($html, 0, $index) . $array[$key] . 
      substr ($html, $closing_index + 4); 

    $index = strpos($html, "<!--", $index + 1); 
} 

참고 :이 테스트되지 않았습니다, 그래서 인덱스 일부 부정확성이있을 수 있습니다 ... 그냥 당신에게 일반적인 아이디어를주고있다.

나는 이것이 str_replace보다 효율적이라고 생각하지만, 무엇을 알고 있는가? 이 일부 벤치마킹을 사용할 수 있습니다 ...

+0

strpos()에 관한 모든 사례가 있습니까? – sakhunzai

+0

@sakhunzai가 strpos 예제를 추가했습니다. –

+0

노력에 감사하지만, 캐시 된 지원이있어 모스 터스가 더 나은 옵션으로 보입니다. – sakhunzai

0

내가 정확하게 질문을 이해한다면, 나는 뭔가를 놓치지 않는 한 다음과 같이 잘 작동해야한다고 생각합니다.

$a = array('name'=>'my full name','address'=>'some address'); 
foreach($a as $k=>$v) 
{ 
    $html = str_replace('<!--{'.strtoupper($k).'}-->',$v,$html); 
} 
+0

예,이 작업을 수행하는 데 '효율적인'방법이 필요합니다. – sakhunzai

관련 문제