2013-04-07 118 views
0

我正在使用模板系統。在這個模板系統中,我使用下面顯示的if-else條件的結構;PHP嵌套如果條件

<if condition="'$condition' != 1"> 
    <div>true source</div> 
</if> 

比我用下面的模式分離表達式;

$pattern_case = '<if condition="(.*?)">(.*?)</if>'; 
preg_match("#$pattern_case#si",$string,$case) 

但有些情況下if-else進程可以在另一個內使用(嵌套的? - recusirve?)例如;

<if condition="'$condition1' != 1"> 
    <div>condition 1 text</div> 
    <if condition="'$condition2' == 2 "> 
     <div>condition 2 text</div> 
    </if> 
    condition 1 text more 
</if> 

在這種情況下,模式提供了以下結果。

<if condition="'$condition1' != 1"> 
    <div>condition 1 text</div> 
    <if condition="'$condition2' == 2 "> 
     <div>condition 2 text</div> 
    </if> 

(所以無此項)

condition 1 text more 
</if> 

不使用DOM文檔如何解決與正則表達式這個問題?

回答

1

你不能。通過設計,正則表達式不能處理遞歸。

欲瞭解更多信息,你可能想在這裏閱讀第一個答案:Can regular expressions be used to match nested patterns?

是的,我知道,有些特殊的「正則表達式」不要允許遞歸。但是,在大多數情況下,這意味着你正在做一些可怕的事情。

0

您可以。 「按照設計,正則表達式不能處理遞歸。」是正確的,但是PCRE提供比嚴格正則表達式語言更多的功能。這就是爲什麼術語「正則表達式」在許多語言中不正確地指代「正則表達式」的原因。

的方式做到這一點:

$subject = <<<'LOD' 
<if condition="'$condition1' != 1"> 
<div>condition 1 text</div> 
<if condition="'$condition2' == 2 "> 
<div>condition 2 text</div> 
</if> 
condition 1 text more 
</if> 
LOD; 
$pattern = '~<if condition="(?<condition>[^"]+)">(?<content>(?:.*?(?R)?)+?)</if>~s'; 
preg_match_all($pattern, $subject, $matches); 
print_r($matches); // see your html source 

此代碼匹配你的嵌套結構。 現在,壞消息是:你無法用單一模式從其他深度捕捉「條件」和「內容」! 一種方法是製作一個遞歸函數,在「內容」上重試模式,並在沒有更多嵌套「if」時停止。請記住,此方法具有巨大的複雜性(在算法意義上)並且最好的方式(你知道)是使用DOM