Simple BBCode Parser with regex
2 posts
Page 1 of 1
This tutorial will show you how to create a really simple BBCode parser using regex.
NOTE: You can use # or /, but I've experienced parsing problems with / before. The only real reason however, is support by other languages.
(Formatted)
Bold Text
Underlined Text
Italic Text
[center]Centered Text[/center]
[center]Text with all formatting applied.[/center]
(Unformatted)
<strong>Bold Text</strong><br />
<u>Underlined Text</u><br />
<i>Italic Text</i><br />
<center>Centered Text</center><br />
<strong><i><u><center>Text with all formatting applied.</center></u></i></strong>
Code: Select all
That's the full code, now to break it down.
function parse_bbcode($string){
$codes = array(
'#\[b\](.*)\[\/b\]#is' => '<strong>$1</strong>',
'#\[i\](.*)\[\/i\]#is' => '<i>$1</i>',
'#\[u\](.*)\[\/u\]#is' => '<u>$1</u>',
'#\[center\](.*)\[\/center\]#is' => '<center>$1</center>'
);
htmlspecialchars($string);
nl2br($string);
foreach($codes as $original => $new){
preg_replace($original,$new,$string);
}
return($string);
}
echo parse_bbcode("[b]Bold Text[/b]\r\n[u]Underlined Text[/u]\r\n[i]Italic Text[/i]\r\n[center]Centered Text[/center]\r\n[b][i][u][center]Text with all formatting applied.[/center][/u][/i][/b]");
Code: Select all
This defines the regex of the original stuff and what to replace it with. The string on the left of the "=>" is the original text in regex form, and the string on the right of the "=>" is the replacement text. $codes = array(
'#\[b\](.*)\[\/b\]#is' => '<strong>$1</strong>',
'#\[i\](.*)\[\/i\]#is' => '<i>$1</i>',
'#\[u\](.*)\[\/u\]#is' => '<u>$1</u>',
'#\[center\](.*)\[\/center\]#is' => '<center>$1</center>'
)
NOTE: You can use # or /, but I've experienced parsing problems with / before. The only real reason however, is support by other languages.
Code: Select all
This function replaces any HTML tags like < with < and so on to make then text-friendly.
htmlspecialchars($string);
Code: Select all
This function does as it says, it converts a newline (\n or \r\n) to <br />.
nl2br($string);
Code: Select all
This piece of code cycles through the $codes array we defined earlier and uses preg_replace(); to replace the text using regex. foreach($codes as $original => $new){
preg_replace($original,$new,$string);
}
Code: Select all
Finally, this will display the following:echo parse_bbcode("[b]Bold Text[/b]\r\n[u]Underlined Text[/u]\r\n[i]Italic Text[/i]\r\n[center]Centered Text[/center]\r\n[b][i][u][center]Text with all formatting applied.[/center][/u][/i][/b]");
(Formatted)
Bold Text
Underlined Text
Italic Text
[center]Centered Text[/center]
[center]Text with all formatting applied.[/center]
(Unformatted)
<strong>Bold Text</strong><br />
<u>Underlined Text</u><br />
<i>Italic Text</i><br />
<center>Centered Text</center><br />
<strong><i><u><center>Text with all formatting applied.</center></u></i></strong>

2 posts
Page 1 of 1
Copyright Information
Copyright © Codenstuff.com 2020 - 2023