Search code examples
phpbbcode

how to get a valid substring from bbcode post


The idea is to have first 80 characters of user post visible in some overview mode. But how do I do that with bbtags?

  • how not to cut string in the middle of bbtag
  • how not to just open tag.
  • I cannot just ignore those tags, because one of them is spoiler :-) (i could ignore simple formatting)

I have absolutely no clue how to do it and quick googling didn't help.

example:

Darth Vader [spoiler]is father of luke skywalker[/spoiler]

If I want substring of 20 characters, I would want this:

Darth Vader [spoiler]is fathe[/spoiler]

Solution

  • Maybe you help this code, it should be further developed, but the idea should be clear:

    $str = 'Darth Vader [spoiler]is father of luke skywalker[/spoiler]';
    
    function parse($str, $count)
    {
        $arr1 = str_split($str);
        $result = [];
        $i = 0;
        $open = false;
        foreach ($arr1 as $chr)
        {
            if ($open || $chr === '[')
            {
                $open = true;
                if ($chr === ']')
                {
                    $result[] = $chr;
                    $open = false;
                }
                else
                {
                    $result[] = $chr;
                }
            }
            elseif($i <= $count)
            {
                $result[] = $chr;
                $i++;
            }
        }
        return implode($result);
    }
    echo parse($str, 20);
    

    You must rewrite code, and test with this case: "][" and "[][[[[[]]][[]][[[["

    Or select other algoritm, and use regex....