2013-03-11 52 views
3

我試圖重新排序BBCodes但我失敗了重排序/重新包裝bbcodes

所以

[B]̶[I]̶​​[U]美孚[̶/ B]̶[̶/ U] ̶[̶/ I]̶̶-̶錯誤的順序̶̶

我希望它是:̶̶

̶[B]̶[I]̶​​[U] FOO [̶/ U]̶[ ̶/̶i̶]̶[̶/̶b̶]̶̶̶̶r̶i̶g̶h̶t̶̶o̶r̶d̶e̶r̶

PIC:enter image description here

我試圖與

<?php 
$string = '[b][i][u]foo[/b][/u][/i]'; 
$search = array('/\[b](.+?)\[\/b]/is', '/\[i](.+?)\[\/i]/is', '/\[u](.+?)\[\/u]/is'); 
$replace = array('[b]$1[/b]', '[i]$1[/i]', '[u]$1[/u]'); 
echo preg_replace($search, $replace, $string); 
?> 

OUTPUT:並[b] [I] [U]富[/ B] [/ U] [/ I]

任何建議?謝謝!

+2

還應該輸出什麼類似'[b] a [i] b [u] foo [/ b] baa [/ u]''?有沒有簡單的方法來實現正確的有序輸出 – Philipp 2013-03-11 13:42:45

+0

@Philipp我希望他們像我的例子那樣排列 – 2013-03-11 13:49:39

+1

@ Philipp提出了一個有效的觀點,因爲他的輸入結果不會是確定性的。你應該考慮它的規則,你的例子是不夠的。 – 2013-03-12 10:00:26

回答

0

phew,花了一段時間思考邏輯來做到這一點。 (隨意把它放在一個功能)

這隻適用於給出的情況。像其他用戶評論說的那樣,這是不可能的。你不應該這樣做。甚至在服務器端。我會使用客戶端解析器只是爲了引發語法錯誤。

支持[b]a[i]b[u]foo[/b]baa[/u]too[/i]

,並設置高亮使用自定義值[url=test][i][u]foo[/url][/u][/i]

將與 [b] bold [/b][u] underline[/u][b] bold [u][/b] underline[/u]打破

//input string to be reorganized 
    $string = '[url=test][i][u]foo[/url][/u][/i]'; 
    echo $string . "<br />"; 

    //search for all opentags (including ones with values 
    $tagsearch = "/\[([A-Za-z]+)[A-Za-z=._%?&:\/-]*\]/"; 
    preg_match_all($tagsearch, $string, $tags); 

    //search for all close tags to store them for later 
    $closetagsearch = "/(\[\/([A-Za-z]+)\])/is"; 
    preg_match_all($closetagsearch, $string, $closetags); 

    //flip the open tags for reverse parsing (index one is just letters) 
    $tags[1] = array_reverse($tags[1]); 
    //create temp var to store new ordered string 
    $temp = ""; 
    //this is the last known position in the original string after a match 
    $last = 0; 
    //iterate through each char of the input string 
    for ($i = 0, $len = strlen($string); $i < $len; $i++) { 
     //if we run out of tags to replace/find stop looping 
     if (empty($tags[1]) || empty($closetags[1])) 
      continue; 
     //this is the part of the string that has no matches 
     $good = substr($string, $last, $i - $last); 
     //next closing tag to search for 
     $next = $closetags[1][0]; 
     //how many chars ahead to compare against 
     $scope = substr($string, $i, strlen($next)); 
     //if we have a match 
     if ($scope === "$next") { 
      //add to the temp variable with a modified 
      //version of an open tag letter to become a close tag 
      $temp .= $good . substr_replace("[" . $tags[1][0] . "]", "/", 1, 0); 
      //remove the first key/value in both arrays 
      array_shift($tags[1]); 
      array_shift($closetags[1]); 
      //update the last known unmatched char 
      $last += strlen($good . $scope); 
     } 
    } 

    echo $temp; 

另請注意:這可能是用戶打算窩標籤故障排除:X

+0

這就是我想要的,謝謝! – 2013-03-14 23:06:30