2014-09-21 30 views
1

我创建了一个模板系统来替换所有以'%%'开头和结尾的变量。问题是,预浸更换有时代替超过它应该,这里有一个例子:preg_replace是否可以替换两个符号之间的所有内容?

<?php 
    $str = "100% text %everythingheregone% after text"; 
    $repl = "test"; 
    $patt = "/\%([^\]]+)\%/"; 
    $res = preg_replace($patt, "", $str); 
    echo $res; 
?> 

这个输出“100文本之后”,它应该输出“100%文本文本之后”。有没有解决这个问题的方法?这非常糟糕,因为如果文档中存在CSS规则,则会使用百分号,并最终替换所有文档。

回答

2

使用负回顾后是匹配的不只是后呈现给号码的所有%符号。

(?<!\d)%([^%]*)\% 

然后用空字符串替换匹配的字符串。

DEMO

$str = "100% text %everythingheregone% after text"; 
$repl = "test"; 
$patt = "/(?<!\d)%([^%]*)\%\s*/"; 
$res = preg_replace($patt, "", $str); 
echo $res; 

输出:

100% text after text 
2

的问题是一个设计缺陷,不应该用一些漂亮的正则表达式来合作周围。考虑为占位符使用唯一标识符,并且只能从允许的变量名称列表中进行匹配。

$str = "100% text {%_content_%}";

而更换使用str_replace()

$res = str_replace("{%_content_%}", "test", $str); 

strtr()多个替代对象:

$replace_map = array(
"{%_content_%}" => "test", 
"{%_foo_%}" => "bar", 
); 

$res = strtr($str, $replace_map); 

只是一个想法为目标的核心问题。


至此更换%containing_word_characters%

$res = preg_replace('~%\w+%~', "test", $str); 

test at regex101

+1

太好了!你注意到关于单词字符的观点是不可思议的。我想了一会儿,然后认定情况可能并非如此。 – Unihedron 2014-09-21 15:57:28

相关问题