\n";
echo "\n";
$out = '';
$open = array();
echo 'Raw input: "'.str_replace(array('<', '>'), array('<', '>'), $in)."\"
\n";
function untag($tag, $open) {
$tags = array('b' => '', '/b' => '',
'u' => '', '/u' => '',
'i' => '', '/i' => '',
'/color' => '');
$colors = array('0','1','2','3','4','5','6',
'7','8','9','a','b','c','d','e','f');
$presets = array('red','green','blue','yellow','purple','black','white','grey');
$tag = strtolower($tag);
if (array_key_exists($tag, $tags)) {// needs to check for an open tag
if ($tag{0} == '/') {// If it's a close tag...
$i = array_search(substr($tag, 1), $open);
if ($i === false)
return array('[', $open);
unset($open[$i]);
} else {// If it's an open tag...
$open[] = $tag;
}
return array($tags[$tag], $open);
}
// Below: Non-simple tags (with parameters, etc.)
if (substr($tag, 0, 6) == 'color:') {
$i = array_search(substr($tag, 6), $presets);
if ($i !== false) {
$open[] = 'color';
return array('', $open);
}
$valid = true;
for($i = 6; $i <= 11; $i++)
if (!in_array($tag{$i}, $colors)) {
$valid = false;
break;
}
if ($valid) {
$open[] = 'color';
return array('', $open);
}
else return array('[', $open);
}
else return array('[', $open);
}
//$in = strip_tags($in);
$in = str_replace(array('<', '>'), array('<', '>'), $in);
while (strlen($in) > 0) {
$i = strpos($in, '[');
if ($i === false) {
$out .= $in;
break;
}
$out .= substr($in, 0, $i);
$in = substr($in, $i);
// Untag script begins here
$i = strpos($in, ']');
if ($i === false) {
$out .= $in{0};
$in = substr($in, 1);
} else {
$tag = substr($in, 1, $i-1);
$in = substr($in, $i+1);
$temp = untag($tag, $open);
$open = $temp['1'];
$out .= $temp['0'];
if ($temp['0'] == '[')
$in = $tag.']'.$in;
}
}
foreach($open as $tag)
$out .= ($tag == 'color') ? '' : ''.$tag.'>';
echo "\n\n
Output: \"".$out.'"
';
?>
Usage:
Mark off text to be formatted with tags like this:
[b]bold[/b]
[i]italic[/i]
[u]underline[/u]
If you try to close a [b] tag when there is none open, the BBCode should be ignored. (So, "[/b]Te[b]st[/b]" would come up as "[/b]Test".) If you don't close your tags, they'll be cleaned up at the end of the input.
You can also choose a font's color using hexadecimal RGB values, or a few presets (red, green, blue, yellow, purple, black, grey and white). Format:
[color:red]red[/color]
[color:ff00ff]magenta??![/color]
Each color (red, green, blue) has a pair of numbers; they are: RRGGBB. You can input numbers from 0-f (in order of value: 0123456789abcdef).
source