2012-08-07 142 views
1

我試圖獲取兩個大括號之間的內容或Smarty標記。我想,只有Smarty的函數變量,忽略if的等正則表達式preg_match PHP

下面是樣本串標籤:

{{$variable|lower}} [亦宜]

{{$variable|escape:javascript}} [亦宜]

{{$variable|str_replace:"search":"replace"}} [亦宜]

{{if $test eq "test"}} [應當NOT是墊高等教育委員會]

{{section name=foo start=10 loop=20 step=2}} [應匹配]

如果我這樣做

preg_match_all('/{{\$?(\w+?[\W\w]*?)}}/',$str,$matches) 

它得到括號內的一切。

preg_match_all('/{{\$?(\w+?\W*?\w*?)}}/',$str,$matches); 

這隻會得到「變量|轉義」。

請幫助正確的正則表達式。

感謝

+2

這是什麼你正在努力實現?這可能比嘗試重新設計已經非常糟糕的Smarty更好。 – 2012-08-07 14:29:07

+0

@Michael我希望我能+10 – DaveRandom 2012-08-07 14:29:41

+0

@DaveRandom我的兩個最大的編程遺憾是圍繞着Smarty構建的。 – 2012-08-07 14:30:49

回答

0

我可能是錯的,但不會簡單地說:

preg_match_all('/\{\{(\$[^|]+)\|[^}]+\}\}/',$str,$matches); 

做的伎倆,在那裏$matches[1]將舉行的變量。如果文件中包含回車(窗口\ r \ n),嘗試'/\{\{(\$[^|]+)\|[^}]+\}\}/s',與s修改

包括像火柴:{{$var}}

//{{$var|foo}} {{$varbar}} bar as test string 
preg_match_all('/\{\{(\$[^|}]+)(\|[^}]+|)\}\}/s',$str,$matches); 
//shorter still: 
preg_match_all('/\{\{(\$[^|}]+)\|?[^}]*\}\}/s',$str,$matches); 

回報:

array (
    0 => 
    array (
    0 => '{{$var|foo}}', 
    1 => '{{$varbar}}', 
), 
    1 => 
    array (
    0 => '$var', 
    1 => '$varbar', 
), 
    2 => //not in the array when using the second pattern 
    array (
    0 => '|foo', 
    1 => '', 
), 
) 
+0

對不起,我忘了提及,但它是否可以只支持{{$ variable}}? – user1105950 2012-08-07 14:48:51

+0

謝謝。你能建議我一些很好的RegEx教程嗎? – user1105950 2012-08-07 16:16:48

+0

那麼,我已經學會了JS控制檯的基礎知識,使用[this site](http://www.regular-expressions.info/)作爲我的主要參考。雖然他們也有一些關於php正則表達式的信息。我也經歷了大量的試驗和錯誤,以便掌握這一切,但[在線功能](http://www.functions-online.com),[writecodeonline](http://writecodeonline.com/php/) )和[codepad](http://codepad.org/)是很好的沙箱...基本上只是留在它,實踐是最好的導師恕我直言。只是閱讀基礎知識,並練習,我不認爲有一個神奇的嘖嘖在那裏...對不起 – 2012-08-07 16:35:10

0

使用正則表達式\{\{.*?\|.*.+?\}\}

+0

對不起,但它沒有匹配 – user1105950 2012-08-07 14:37:59