Reputation: 2097
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
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.
Upvotes: 0
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:
[b], [i] etc
)Upvotes: 1