2014-09-21 32 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

相關問題