Skip to content

Instantly share code, notes, and snippets.

@luckydevilru
Forked from afsalrahim/php_bbcode_parser.php
Last active October 11, 2021 16:04
Show Gist options
  • Save luckydevilru/dd6d4da8a7b72b664125f98c1b53189f to your computer and use it in GitHub Desktop.
Save luckydevilru/dd6d4da8a7b72b664125f98c1b53189f to your computer and use it in GitHub Desktop.
A simple PHP BBCode Parser function
<?php
/**
* A simple PHP BBCode Parser function
*
* @author Afsal Rahim
* @link http://digitcodes.com/create-simple-php-bbcode-parser-function/
**/
//BBCode Parser function
function BBToHtml($text)
{
$text = strip_tags($text);
// BBcode array
$find = array(
'~\[b\](.*?)\[/b\]~s',
'~\[i\](.*?)\[/i\]~s',
'~\[u\](.*?)\[/u\]~s',
'~\[quote\]([^"><]*?)\[/quote\]~s',
'~\[size=([^"><]*?)\](.*?)\[/size\]~s',
'~\[color=([^"><]*?)\](.*?)\[/color\]~s',
'~\[url=([^"><]*?)\](.*?)\[/url\]~s',
'~\[img\](https?://[^"><]*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s'
);
// HTML tags to replace BBcode
$replace = array(
'<b>$1</b>',
'<i>$1</i>',
'<span style="text-decoration:underline;">$1</span>',
'<pre>$1</'.'pre>',
'<span style="font-size:$1px;">$2</span>',
'<span style="color:$1;">$2</span>',
'<a href="$1">$2</a>',
'<img src="$1" alt="" />'
);
// Replacing the BBcodes with corresponding HTML tags
return preg_replace($find, $replace, $text);
}
// How to use the above function:
$bbtext = "This is [b]bold[/b] and this is [u]underlined[/u] and this is in [i]italics[/i] with a [color=red] red color[/color]. Напоминание о событии [url=https://bx24.wtcmoscow.ru/company/personal/user/1537/calendar/?EVENT_ID=54795&EVENT_DATE=11.10.2021]test[/url], 11.10.2021 18:55";
$htmltext = showBBcodes($bbtext);
echo $htmltext;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment