Skip to content

Instantly share code, notes, and snippets.

@timint
Created October 30, 2024 16:16
Show Gist options
  • Save timint/dbfbed95c874a17ffec633b09f819c12 to your computer and use it in GitHub Desktop.
Save timint/dbfbed95c874a17ffec633b09f819c12 to your computer and use it in GitHub Desktop.
PHP function to convert bbcode to markdown using preg_replace()
<?php
function bbcode_to_markdown($input) {
$result = $input;
foreach ([
'#(\r\n?|\n)#s' => '\n', // Neutralize line breaks
'#\s*\[hr\]\s*#s' => "\n_____\n",
'#\[b\](.*?)(\[/b\]\s*|$)#s' => "**$1**",
'#\[u\](.*?)(\[/u\]\s*|$)#s' => "<u>$1</u>",
'#\[i\](.*?)(\[/i\]\s*|$)#s' => "__$1__",
'#\s*\[li\](.*?)\[/li\]\s*#s' => "\n * $1\r\n",
'#\s*\[ol\](.*?)(\[/ol\]\s*|$)#s' => "\n\n$1\n\n",
'#\s*\[ul\](.*?)(\[/ul\]\s*|$)#s' => "\n\n$1\n\n",
'#\s*\[list\](.*?)(\[/list\]\s*|$)#s' => "\n\n$1\n\n",
'#\[code[^\]*]\](.*?)(\[/code\]|$)#s' => "```$1```",
'#\[font[^\]*]\](.*?)(\[/font\]|$)#s' => "$1",
'#\[url](.*?)(\[/url\]|$)#s' => "[$1]($1)",
'#\[url=([^\]]*)]\](.*?)(\[/url\]|$)#s' => "[$2]($1)",
'#\[img](.*?)(\[/img\]|$)#s' => "![]($1)",
'#\[img=([^\]]*)]\](.*?)(\[/img\]|$)#s' => "![$2]($1)",
'#[\t ]+([\r\n]*)$#m' => '$1', // Trim trailing space
'#\n\n+#s' => '\n\n', // Remove exceeding line breaks
] as $pattern => $replace) {
$result = preg_replace($pattern, $replace, $result);
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment