2014-01-27 2 views
1

{tag}과 같은 태그를 검색하고로드 할 때 템플릿 파일의 내용으로 동적으로 바꿔주는 템플릿 시스템을 개발했습니다.두 번 검색하고 바꾸는 방법

{다운로드} <a class="button">Download</a>이 {다운로드 = '버튼 텍스트를'} 반환 무엇 IM이 {download='text for button'}

같은 태그가 아래에 내 모든 태그 동안

//Download button 
$download = '<a class="button">Download</a>'; 
$search = "{download}"; 
if (contains($string,$search)) 
    $string=str_ireplace($search,$download,$string); 

그래서 시작하는 방법입니다 수 있도록되어 일을하려고

반환해야합니다 <a class="button">button text</a>

+0

아이디어는 훌륭하지만 왜 바퀴를 재발 명합니까? – ex3v

+0

설치가 쉽기 때문에 사용자는 기본적으로 html/css를 사용하여 자신의 템플릿을 만들 수 있지만 특정 것들은이 태그를 사용하여 동일하게 만들어집니다. –

답변

1

아마도 하나?

<?php 

    $str = '{download} button {download="hello"} {download=\'hey\'} assa {download="asa"}'; 

    $str = str_replace('{download}', '{download="Download"}', $str); 

    $str = preg_replace(
     '/\{download(\=\"(.*)\"|\=\'(.*)\'|)\}/siU', 
     '<a href="#" class="button">$2</a>', 
     $str); 

    echo $str; 

?> 
+0

완전히 작동하는 예제를 넣었으므로 $ str을 "검색"하려는 문자열로 바꿉니다. –

+0

$ str = str_replace ('{download}', '{download = "다운로드"}', $ str)에 혼란 스러움; 그게 뭐야? –

+0

Mr. Johnson,이 줄을 바꾸면 단추에는 기본 텍스트가 사용되지 않습니다. 이것은 핵심 작업을 수행하기 전에 {download} 코드를 {download = "Download"}로 바꾸는 것입니다. –

1
preg_match_all("/{download='(.*?)'}/", $string, $matches, PREG_SET_ORDER); 

foreach ($matches as $val) { 
    $string = str_replace("{download='" . $val[1] . "'}", "<a class=\"button\">" . $val[1] . "</a>", $string); 
} 

이 작동합니다.

예 : - ex3v 말했듯이 - http://3v4l.org/cl1aI

1

흠이 하나 너무 나를 위해 '바퀴를 개혁'문제와 같은 약간 것 같다,하지만 난 좀 그것을 좋아, 그래서 나는 주위를 연주 조금 있지만 정규식이 없으면 좀 더 일반적인 솔루션이 되길 원했기 때문에 사용자 정의 속성을 사용할 수 있습니다 (하지만 공백 값은 속성 값으로 사용하지 않음). 그래서 결국 다음과 같이 끝났습니다.

<?php 

function use_template($search,$replace,$string, $options=array()) { 

    $searchdata = explode(" ", $search); //{download, text='Fancy'} 
    $template = substr($searchdata[0],1); // download 


    for ($i = 1; $i < sizeof($searchdata);$i++) { 
     $attribute = explode("=", $searchdata[$i]); //$attribute[0] = "text"; $attribute[1] = "'Fancy'}" 
     if (endsWith($attribute[1],'}')) { 
      $options[$attribute[0]] = substr($attribute[1], 0, -1); 
     } else { 
      $options[$attribute[0]] = $attribute[1]; 
     } 
    } 

    $a = str_ireplace("{".$template."}",$replace,$string); // Hello, this is my {<a class="button">[text]</a>} button 
    foreach($options as $to_replace => $newval) { 
     $a = str_ireplace("[".$to_replace."]", $newval, $a); // Hello, this is my Fancy button 
    } 
    return $a; 
} 

function endsWith($haystack, $needle) 
{ 
    return $needle === "" || substr($haystack, -strlen($needle)) === $needle; 
} 

$download = '<a class="button" style="background-color: [color];">[text]</a>'; 
$search = "{download text='Fancy' color=red}"; 
$string = "Hello, this is my {download} button!"; 
$options = array("text" => "Download", "color" => "#000000"); 


$string= use_template($search,$download,$string,$options); 
echo $string; 
?> 
+0

이것도 좋습니다 –

관련 문제