我如何搜索和替换两次

时间:2014-01-27 14:32:06

标签: php replace

我开发了一个模板系统,用于搜索{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);

因此,当{download}返回<a class="button">Download</a>时,{download =&#39;按钮文字&#39;}应该返回<a class="button">button text</a>

3 个答案:

答案 0 :(得分: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;

?>

答案 1 :(得分: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

答案 2 :(得分: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;
?>