2012-09-03 80 views
1

我怎麼能代替:PHP的BBCode正則表達式替換

<tag attr="z"> 
    <tag attr="y"> 
     <tag attr="x"></tag> 
    </tag> 
</tag> 

到:

<tag attr="z"> 
    [tag=y] 
     <tag attr="x"></tag> 
    [/tag] 
</tag> 

不使用擴展?

我不成功的嘗試:

preg_replace("#<tag attr=\"y\">(.+?)</tag>#i", "[tag=y]\\1[/tag]", $text); 
+0

的preg_replace( 「#<標籤ATTR = \」 Y \「>(+)#我「,」[tag = y] \\ 1 [/ tag]「,$ text); – Bestudio

+0

點擊「編輯」有更多的信息來更新你的問題,這是很容易,評論閱讀。 – Jocelyn

回答

2

那麼,PHP的正則表達式實現支持PCRE的遞歸模式。但是,由於其神祕性質,我會猶豫使用這樣的功能。但是,既然你問:

不使用擴展?

在這裏它是:

<?php 

$html = '<tag attr="z"> 
    <tag attr="y"> 
     <tag> 
      <tag attr="more" stuff="here"> 
       <tag attr="x"></tag> 
      </tag> 
     </tag> 
    </tag> 
</tag> 
'; 

$attr_regex = "(?:\s+\w+\s*=\s*(?:'[^']*'|\"[^\"]*\"))"; 
$recursive_regex = "@ 
    <tag\s+attr=\"y\">   # match opening tag with attribute 'y' 
    (       # start match group 1 
     \s*      # match zero or more white-space chars 
     <(\w+)$attr_regex*\\s*> # match an opening tag and store the name in group 2 
     (      # start match group 3 
     [^<]+     #  match one or more chars other than '<' 
     |      #  OR 
     (?1)     #  match whatever the pattern from match group 1 matches (recursive call!) 
    )*      # end match group 3 
     </\\2>     # match the closing tag with the same name stored in group 2 
     \s*      # match zero or more white-space chars 
    )       # end match group 1 
    </tag>      # match closing tag 
    @x"; 

echo preg_replace($recursive_regex, "[tag=y]$1[/tag]", $html); 

?> 

這將打印以下:?

<tag attr="z"> 
    [tag=y] 
     <tag> 
      <tag attr="more" stuff="here"> 
       <tag attr="x"></tag> 
      </tag> 
     </tag> 
    [/tag] 
</tag> 
+0

+1爲漂亮的正則表達式的對決。 – moonwave99

+0

哇!非常感謝! – Bestudio

+0

爲什麼我不能運行這個正則表達式代碼兩次? – Bestudio