重新排序/重新封装bbcodes

时间:2013-03-11 13:30:22

标签: php html

我正在尝试重新排序BBCodes,但我失败了

所以

[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶b̶]̶[̶/̶u̶]̶[̶/̶i̶]̶̶-̶̶w̶r̶o̶n̶g̶̶o̶r̶d̶e̶r̶̶̶

I̶̶w̶a̶n̶t̶̶i̶t̶̶t̶o̶̶b̶e̶:̶̶

̶[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶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); 
?>

输出: [b] [i] [u] foo [/ b] [/ u] [/ i]

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:0)

phew,花了一段时间思考这样做的逻辑。 (随意把它放在一个函数中)

这仅适用于给定的方案。像其他用户一样评论它是不可能的。你不应该这样做。甚至在服务器端。我使用客户端解析器只是为了抛出语法错误。

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

和bbcode,其中包含自定义值[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