2012-11-27 23 views
0

的我用這個模式:PHP的正則表達式的任何字符

'/({for) (\d+) (times})([\w+\d+{}]{0,})({endfor})/i' 

轉換

{for 3 times}App2{endfor} 

App2 App2 App2 

但這不工作:

{for 7 times} 
    App2 
{endfor} 

這是我很小的模板引擎的一小部分。

這只是爲了好玩

$mactos = Array(
    '/({for) (\d+) (times})([\w+\d+{}]{0,})({endfor})/i' => '<?php for($i=0;$i<${2};$i++) : ?> ${4} <?php endfor; ?' . '>', 
    '/({{)(\w+)(}})/i' => '<?php echo $${2}; ?' . '>' 
); 
$php = file_get_contents('teamplate.php'); 
foreach ($this->getPatternAndReplacement() as $pattern => $replacement) { 
    $php = preg_replace($pattern, $replacement, $php); 
} 

我讀過,(...)捕捉到任何但是

'/({for) (\d+) (times})(...)({endfor})/i' 

不起作用=(

+0

邊注:大多數的元字符失去字符類中的特殊含義,所以你讓文字'+'字符。假設你不想接受字面值'+'字符,'[\ w + \ d + {}] {0,}'似乎相當於'[\ w {}] *'(因爲'*' 0,}'和'\ d'被包含在'\ w'中。 – Wiseguy

回答

2

如果您的字面意思是(...),那就是ag羣恰好匹配三個字符。 (.+)將匹配一個或多個任意字符,除了...


默認情況下,.匹配任何除了換行。

S(PCRE_DOTALL)
如果設定了此修正,在模式中的圓點元字符的所有字符,包括換行匹配。沒有它,換行符被排除在外。

使用s modifier來允許.匹配換行符。

/your pattern/s 

實例(也here

$str = <<<STR 
{for 7 times} 
    App2 
{endfor} 
STR; 

preg_match('/({for) (\d+) (times})(.+)({endfor})/s', $str, $matchParts); 

print_r($matchParts); 
OUTPUT: 

Array 
(
    [0] => {for 7 times} 
    App2 
{endfor} 
    [1] => {for 
    [2] => 7 
    [3] => times} 
    [4] => 
    App2 

    [5] => {endfor} 
) 
+0

'/({for)(\ d +)(times})(。+)({endfor})/ s'不起作用 – sensorario

+0

似乎對我來說沒問題。看[這裏的例子](http://codepad.viper-7.com/aHyru2)。 – Wiseguy

+0

這沒關係,但我想明白爲什麼沒有兩個像工作:$海峽= <<< STR {7}次 應用2 {} ENDFOR { 7次} 應用2 {ENDFOR } STR; – sensorario