Php preg_用类分隔符Var替换{*..}

Php preg_用类分隔符Var替换{*..},php,preg-replace,Php,Preg Replace,我用PHP编写了一个小模板类 模板类使用分隔符替换变量 例如,一个简单的模板 {$WEBSITE_TITLE} 如果我没有指定占位符,它们将保留在站点源代码中。 但作为一个例子,我有一个注释标签,如果我没有分配它们,用户不应该看到它们 如果我不知道{$…}中的内容,如何用零替换该文本 {$/一些我们不知道的文本/} 我当时试了很多。我的此操作代码是: preg_replace( "/\/$this->_leftDelimiter(.*?)$this->_rightDelimi

我用PHP编写了一个小模板类

模板类使用分隔符替换变量

例如,一个简单的模板

{$WEBSITE_TITLE}

如果我没有指定占位符,它们将保留在站点源代码中。 但作为一个例子,我有一个注释标签,如果我没有分配它们,用户不应该看到它们

如果我不知道{$…}中的内容,如何用零替换该文本

{$/一些我们不知道的文本/}

我当时试了很多。我的此操作代码是:

preg_replace(
    "/\/$this->_leftDelimiter(.*?)$this->_rightDelimiter/",
    "",
    $this->_template
);
类分隔符变量:

private $_leftDelimiter = '{$';
private $_rightDelimiter = '}';

您可能应该将类变量和分隔符放在字符串之外:

preg_replace(
    "/".$this->_leftDelimiter."([^".$this->_rightDelimiter."]*?)".$this->_rightDelimiter."/",
    "",
    $this->_template
);
您应该使用函数,该函数允许您根据匹配字符串的内容替换匹配字符串

function teplateVars($matches) {
    // your logic here
    return $this->getStringForVariable($matches[1]);
}
preg_replace(
    "/".$this->_leftDelimiter."([^".$this->_rightDelimiter."]*?)".$this->_rightDelimiter."/",
    "templateVars",
    $this->_template
);
还要确保_leftDelimiter和_righDelimiter属性已正确转义,以便可以在正则表达式中使用。开头括号和美元符号具有特殊含义

private $_leftDelimiter = '\{\$';
private $_rightDelimiter = '}';
允许在标记中有}吗?e、 g.{$foo}bar}?-作为ana方面,我会考虑将leftDelimiter/rightDelimiter包装起来,以避免出现问题。