Created
October 30, 2024 16:16
-
-
Save timint/dbfbed95c874a17ffec633b09f819c12 to your computer and use it in GitHub Desktop.
PHP function to convert bbcode to markdown using preg_replace()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' => "", | |
'#\[img=([^\]]*)]\](.*?)(\[/img\]|$)#s' => "", | |
'#[\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