NaughtySquid
NaughtySquid

Reputation: 2097

a way to strip incomplete bbcode?

Is there a way in php to search for bbcodes like [b][/b].

For example where they don't have a closing tag? Say for showing snippets of a text reply in an email subscription cut down to x characters might cut off BB-Code leaving it open?

To be used with PHP.

Upvotes: 1

Views: 443

Answers (2)

Hexodus
Hexodus

Reputation: 12927

I wrote a function that will tell you if there're some unclosed bb-tags inside the string. Though it can't tell the position it tells which tags has errors so it's easier to find them. It also finds complex bb-tags like [url=something]urlname[/url]

<?PHP
$test_string = "
    [b]bold ok[/b]
    [b]bold unclosed[b]
    [i]italic unclsed[i]
    [i]italic[/i]
";

echo checkBBCode($test_string);

//------------------------------------

function checkBBCode($str)
{
    $result = "";

    $taglist = array("b", "i", "u", "h1", "h2", "url"); //the bb-tags to search for
    $result_array = array();

    foreach($taglist as $tag )
    {
        // How often is the open tag?  
        preg_match_all ('/\['.$tag.'(=[^ ]+)?\]/i', $str, $matches);  
        $opentags = count($matches['0']);  

        // How often is the close tag?  
        preg_match_all ('/\[\/'.$tag.'\]/i', $str, $matches);  
        $closetags = count($matches['0']);  

        // how many tags have been unclosed? 
        $unclosed = $opentags - $closetags;  
        $unclosed = (int)$unclosed*-1; //force positive values


        $result_array[] = $tag." :".$unclosed;
    }

    foreach($result_array as $check)
    {
        $result .= "\n\r<br>".$check;
    }
    return $result;
}


?> 

I found on dreamincode.net an useful script that has a different approach working in frontend and showing the improper tags visually by highlighting them.

bb_check live demo

bb_check full article

Upvotes: 0

Kasyx
Kasyx

Reputation: 3200

You can Parse bbcode string. Its quite complex, but you can implement naive algorithm to provide Syntactic Analysis. In that way you can get all errors like unclosed tags or wrong order in tag closing, in example:

[b] 
    [i] 
    [/b]
[/i]

The simplest way:

  1. Prepare tag lists ([b], [i] etc)
  2. Search first tag and add it on the stack
  3. Keep looking, and if there is more opening tags, push them on stack too.
  4. When you find closing tag, check what is on top of the stack. There should be correct opening tag. If not, then you find what are you looking for. If closing tag fits, then you can pop last element and keep parsing.

Upvotes: 1

Related Questions