2013-06-18 1 views
1

이전에 $ obj-> html을 출력했지만 현재 프로젝트에서는 {whatever}과 같은 슬러그를 검사하여 다른 내용으로 바꾸어야합니다.정규 표현식의 속도 향상 및 슬러그에 대한 preg_replace 사용

두 가지 문제점이 있습니다. 첫 번째는이 코드가 내가 원하는 것보다 느리다는 것입니다 :

class Foo { 

    function draw_content() { 
    $slug = "/(?<=\{).*(?=\})/"; 
    if (preg_match($slug, $this->html, $matches)) { 
     foreach ($matches as $match) { 
      if (method_exists($this,$match)) { 
       $replacement = $this->$match(); 
       $this->html = preg_replace("/\{$match\}/", $replacement, $this->html); 
      } 
     } 
    } 
    return $this->html; 
} // fn 

    function new_releases() { 
    echo "new release book covers"; 
    } // fn 

} // class 

슬러그 내용을 얻는 더 좋은 방법이 있습니까? 나는 정규식이 이것을 늦추는 것으로 추정한다.

두 번째 문제는 저에게 낯선 것입니다. 이 $를 OBJ> HTML 주어 :

<p class="headline">New Releases</p> 
<p>xxx{new_releases}xxxx</p> 

$를 OBJ의 처리 된 출력> draw_content()를 왜 new_releases() 출력이 미리 결정되어 <?=$obj->draw_content()?>

new release book covers<p class="headline">New Releases</p> 
<p>xxxxxxx</p> 

의해 그려진? 민달팽이는 없어졌지만 대체물은 그 자리에 없습니다!

답변

1

당신하여 패턴을 대체 할 수

$slug = '~{\K[^}]*+(?=})~'; 

IMHO, 당신이 당신의 preg_match 테스트 및 유일 preg_replace_callback 기능하여 preg_replace를 교체해야, 이런 식으로 뭔가를 시도 (그리고 버그를 :) 수정합니다.

function draw_content() { 
    $slug = '~{([^}]*+)}~'; 
    $that = $this; 
    $this->html = preg_replace_callback($slug, function ($m) use ($that) { 
     if (method_exists($that, $m[1])) 
      return $that->$m[1](); 
     return $m[0]; }, $this->html); 
    return $this->html; 
} 
+0

와우, 그게 더 빠르네! 고맙습니다! 이상한 preg_replace() 동작에 대한 의견이 있으십니까? – jerrygarciuh

+0

너 락! 나는'preg_replace_callback()'문서를 통해 머리를 긁적 거렸다. 그건 내 문제를 절대적으로 해결해 줬어! – jerrygarciuh

+1

@ jerrygarciuh : 행복합니다. –