2014-01-27 31 views
1

我开发了一个模板系统,用于搜索{tag}之类的标签,并在加载时动态替换模板文件中的内容。如何搜索并替换两次

什么即时试图做的就是这样的{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">Download</a>这个{下载=“按钮文本”}应该返回<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 =“Download”}',$ str);这是为了什么? –

+0

Johnson先生,如果您替换此行,该按钮将永远不会有默认文本。这是在做任何核心工作之前用{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); 
} 

这应该工作。

例子: http://3v4l.org/cl1aI

1

嗯,这一个 - 为ex3v说 - 似乎是对我来说就像“重新发明轮子”的问题有点过,但我还挺喜欢它,所以我周围玩一点点,但没有正则表达式,因为我希望它是一个更通用的解决方案,它启用了自定义属性(但没有空格作为属性值)。所以它结束了这样的:

<?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

这也是伟大的 –