Skip to content

Instantly share code, notes, and snippets.

@krmgns
Last active August 29, 2015 14:13
Show Gist options
  • Save krmgns/6fc38b96a54dbaefbbd9 to your computer and use it in GitHub Desktop.
Save krmgns/6fc38b96a54dbaefbbd9 to your computer and use it in GitHub Desktop.
$str = <<<EOT
Lorem [a href="#"]ipsum[/a] [hr color="red" /] dolor...
[style].foo{color:#fff}[/style]
EOT;
function bbcode_convert($content) {
// remove style|script
$content = preg_replace(
'~(\[(style|sctript)\s?.*\](.*)\[/(\\2)\]|\[(%s)\s?.*/\])~ims', '', $content);
// remove attributes
// src,style, <link href> etc..
$content = preg_replace_callback(
'~(\[([\w\d]+)(?:\s+(.+)|)\](.+?)\[/([\w\d]+)\])|(\[(\w+)(?:\s+(.+)|)/\])~ims',
function($m) {
$attrs = '';
if (isset($m[8]) && $m[8] != '') $attrs = ' '. trim($m[8]); else
if (isset($m[3]) && $m[3] != '') $attrs = ' '. trim($m[3]);
// Self-closing tags
if (isset($m[6], $m[7])) {
return sprintf('<%s%s />', $m[7], $attrs);
}
// Regular tags
if (isset($m[2], $m[4], $m[5]) && $m[2] == $m[5]) {
return sprintf('<%s%s>%s</%s>', $m[2], $attrs, $m[4], $m[2]);
}
}, $content);
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment