PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Mon Nov 18, 2019 8:17 pm

All times are UTC - 5 hours




Post new topic Reply to topic  [ 21 posts ]  Go to page 1, 2  Next
Author Message
 Post subject: Simple BBTag Parser
PostPosted: Sun Jun 04, 2006 11:51 am 
Offline
Tranquility In Moderation
User avatar

Joined: Sun Feb 06, 2005 8:18 pm
Posts: 5001
Location: Indiana
I was just bored and wrote something that might be useful to some people. It's a simple bb tag parser to convert common bb tags to html, and vice versa.

Currently replaces..

B,I,U,QUOTE,IMG, & URL

and.. converts them back to normal text.

bbtags.class.php
Syntax: [ Download ] [ Hide ]
 
<?php
 
/*
* This class will parse the common bbtags B U I URL IMG & QUOTE
* into suitable HTML equivalents and can also reverse them.
*
* Works with PHP >= 4.05
*
* author: scottayy@gmail.com
* date: June 4th, 2006
* update: June 5th, 2006
*   - converting and reversing called in one function (convertBB)
*   - replacing all bb tags combined into one function (replaceTags)
*   - reversing all html tags back to bb combined into one function (reverseTags)
*   - defining our tags called in one function (defineTags)
*/

 
class parseBB {
 
 
    var $basictags;
    var $basicreplacements;
 
   
   
   
 
    /*
    *   function called to turn bb tags into html tags
    *   and called with a FALSE boolean to do the opposite
    *
    *   @param str $text
    *   @param boolean
    */

   
    function convertBB($text,$normal=TRUE){
 
        //define our tags
        $this->defineTags();
 
        //normal or reverse conversion?
        if($normal === TRUE)
            return $this->replaceTags($text);
        else
            return $this->reverseTags($text);
   
    }
 
 
   
   
 
 
    //used internally, does the actual conversion from bb to html
    function replaceTags($text){
 
        //replace basic bbcode bold, underline, italics and quote
        $text = str_replace($this->basictags,$this->basicreplacements,$text);
       
        //replace [url=...]...[/url] bbcode
        if(preg_match("^\[url=(.+?)\](.+?)\[/url\]^im",$text,$urls)){
           
            $text = preg_replace_callback('^\[url=(.+?)\](.+?)\[/url\]^im',
                create_function('$urls',
                    'return \'<a href="\'.trim($urls[1]).\'" target="_blank">\'.trim($urls[2]).\'</a>\';'
                ),
            $text);
           
        }
 
        //replace url bbcode
        if(preg_match("^\[url\](.+?)\[/url\]^im",$text,$urls2)){
           
            $text = preg_replace_callback('^\[url\](.+?)\[/url\]^im',
                create_function('$urls2',
                    'return \'<a href="\'.trim($urls2[1]).\'" target="_blank">\'.trim($urls2[1]).\'</a>\';'
                ),
            $text);
       
        }
 
        //replace img tags
        $text = preg_replace_callback('^\[img\](.+?)\[/img\]^im',
            create_function('$matches',
                'return \'<img src="\'.trim(htmlentities($matches[1],ENT_QUOTES)).\'" alt="Image">\';'
            ),
        $text);
 
        return $text;
 
    }
 
 
   
   
   
   
    //used internally, reverses html back to bbcode
    function reverseTags($text){
       
        //reverse basic html to bold, underline, italics & quote bbcode tags
        $text = str_replace($this->basicreplacements,$this->basictags,$text);
       
        //reverse url tags
        if(preg_match_all("#<a href=\"(.+?)\" target=\"_blank\">(.+?)</a>#im",$text,$rurls)){
        $i=0;
            foreach($rurls[0] AS $url){
                $text = str_replace($url,"[url={$rurls[1][$i]}]{$rurls[2][$i]}[/url]",$text);
                $i++;
            }
        }
 
        //reverse img tags
        if(preg_match_all("#<img src=\"(.+?)\" alt=\"Image\">#im",$text,$imgs)){
            $i=0;
            foreach($imgs[0] AS $imglink){
                $text = str_replace($imglink,"[img"."]{$imgs[1][$i]}[/img]",$text);
                $i++;
            }
        }
       
        return $text;
   
    }
       
   
   
   
   
   
    function defineTags(){
           
        //define $basictags
        $this->basictags = array(
            '<span style="font-weight: bold">',
            '[B]',
            '<span style="font-style: italic">',
            '[I]',
            '<span style="text-decoration: underline">',
            '[U]',
            '</span>',
            '[/B]',
            '</span>',
            '[/I]',
            '</span>',
            '[/U]',
            '[quote'.']',
            '[quote'.']',
            '[/quote]',
            '[/quote]'
        );
           
        //define $basicreplacements
        $this->basicreplacements = array(
            '<b>',
            '<b>',
            '<i>',
            '<i>',
            '<u>',
            '<u>',
            '</b>',
            '</b>',
            '</i>',
            '</i>',
            '</u>',
            '</u>',
            '<blockquote>',
            '<blockquote>',
            '</blockquote>',
            '</blockquote>'
        );
    }
 
 
}
 
?>
 




Sample Usage:
Syntax: [ Download ] [ Hide ]
 
<?php
 
require 'bbtags.class.php';
$bb = new parseBB();
 
$raw = "[b"."]text[/b] [i"."]test[/i] [u"."]test[/u] [b"."][u"."][i"."]test[/i][/u][/b]
[img"
."]http://forums.devnetwork.net/templates/subSilver/images/logo_phpBB.gif[/img]
[quote"
."]yo, i'm a quote![/quote][/quote] [url"."]http://www.showmypro.com[/url] [url"."=http://www.yahoo.com]Yahoo[/url]";
 
$bbalized   = $bb->convertBB($raw);
$regular    = $bb->convertBB($bbalized,FALSE);
 
echo $bbalized.'<br /><br />'.$regular;
 
?>
 


Edit: Those links in the sample are url bb tags.

_________________
- A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.


Last edited by feyd on Fri Aug 01, 2008 10:18 am, edited 7 times in total.
fix php tags.


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jun 04, 2006 1:05 pm 
Offline
Forum Contributor
User avatar

Joined: Wed May 31, 2006 9:20 am
Posts: 393
Location: The Holy Land
Great code!!!

P.S
You can put "& # 9 1 ;" (without the spaces) instead of [ in the sample usage part, i.e:
=> [url]http://www.google.com[/url]


Top
 Profile  
 
 Post subject: Re: Simple BBTag Parser
PostPosted: Sun Jun 04, 2006 1:16 pm 
Offline
Site Administrator
User avatar

Joined: Wed Aug 25, 2004 7:54 pm
Posts: 13592
Location: New York, NY, US
One quick improvement would be to get rid of the function call to get the tags and replacements is creating the arrays in the constructor. It also might be better to use an associative array to keep the pairs together -- and make it less error prone when adding more.

It also seems like you could have a single tag replacement method and have the specific replacement ones call it will just the appropriate values.
Syntax: [ Download ] [ Hide ]
 
<?php
 
class parseBB {
    var $basictags;
    var $basicreplacements;
 
    function parseBB(){
        $this->basictags = array(
            '[b'.']','[B'.']','[i'.']','[I'.']','[u'.']','[U'.']','[/b]','[/B]',
            '[/i]','[/I]','[/u]','[/U]','[quote'.']','[quote'.']','[/quote]','[/quote]');
             $this->basicreplacements = array('<b>','<b>','<i>','<i>','<u>','<u>','</b>','</b>',
        '</i>','</i>','</u>','</u>','<blockquote>','<blockquote>','</blockquote>','</blockquote>');
       }
   
    //function called to turn bb tags into html tags
    function text2BB($text){
   
        //replace them
        $ret = str_replace($this->basictags, $this->basicreplacements, $text);
       
...
 
// get rid of getBasicTags() and getBasicReplacements()
}
?>
 

_________________
(#10850)


Last edited by feyd on Fri Aug 01, 2008 10:19 am, edited 1 time in total.
fix php tags.


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jun 04, 2006 4:08 pm 
Offline
Tranquility In Moderation
User avatar

Joined: Sun Feb 06, 2005 8:18 pm
Posts: 5001
Location: Indiana
Thanks.

I took up your suggestion aborint. And the entity for a bracket didn't work inside the PHP code. I don't think the bbtags should be parsed inside there. Perhaps its an error with the PHP mod.

_________________
- A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 05, 2006 6:02 pm 
Offline
Tranquility In Moderation
User avatar

Joined: Sun Feb 06, 2005 8:18 pm
Posts: 5001
Location: Indiana
A quick thought. If you're running php >= 5, this could easily be made a bit more effective by using in place of the str_replace calls

_________________
- A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 05, 2006 6:23 pm 
Offline
Site Administrator
User avatar

Joined: Wed Aug 25, 2004 7:54 pm
Posts: 13592
Location: New York, NY, US
In looking at the code it looks like you could reduce things down by reusing functions and passing some parameters. The methods reverseURLTags() and reverseURLTags() are identical except for two strings which could be parameters. Likewise replaceURLTags() appears to call twice the same code that is in replaceIMGTags() with only a few strings different. You could probably get it down to just replaceTags() and reverseTags() and pull the misc code back in to the main functions.

Also maybe calling the main functions bb2html() and html2bb() might be clearer.

_________________
(#10850)


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 05, 2006 7:52 pm 
Offline
Tranquility In Moderation
User avatar

Joined: Sun Feb 06, 2005 8:18 pm
Posts: 5001
Location: Indiana
I took up your suggestions again aborint... if the changes are indeed what you meant. I'm kind of proud of this one. Feel like I did something useful for someone. ;)

The main function is now called like convertBB($text); to convert bb to html... and is called with a false parameter to do the opposite. convertBB($text,FALSE);

_________________
- A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.


Top
 Profile  
 
 Post subject: CODE parsing
PostPosted: Tue Jun 06, 2006 7:39 am 
Offline
Forum Contributor
User avatar

Joined: Sun May 07, 2006 5:19 am
Posts: 101
Well this does not appear to NOT parse the [ CODE ] BBTag or a BBTag for direct HTML, etc.. But for simple use, its fine....

I suggest you make lists as well now, as they are very simple.

I made a BBCode2HTML Converter using Javascript in an hour that parses most bbcode so PHP should be much easier.

Nice work upto now though.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 06, 2006 9:15 am 
Offline
Forum Contributor
User avatar

Joined: Tue May 23, 2006 10:42 am
Posts: 351
Just a friendly suggestion, but instead (or alongside) of explicitly defining which tags to replace, maybe add a member function that you can completely customize what tags are replaced. Not only can you add custom tags this way, but you can customize their display style within the tag replacement itself (instead of the CSS flat file).

Syntax: [ Download ] [ Hide ]
 
function addTag($tag, $replace) {
    $this->basictags[] = $tag;
    $this->basicreplacements[] = $replace;
}
 


Just a thought!

- Moose


Last edited by feyd on Fri Aug 01, 2008 10:19 am, edited 1 time in total.
fix php tags.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 06, 2006 9:17 am 
Offline
Her Royal Site Adminness
User avatar

Joined: Tue Apr 23, 2002 2:21 am
Posts: 5371
Location: Essex, UK
Do be careful with using str_replace() to convert bbcode - if closing tags are missing it can cause all sorts of formatting weirdness...

Mac


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 06, 2006 9:27 am 
Offline
Tutorials Group

Joined: Sun Jan 04, 2004 11:30 pm
Posts: 2692


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 06, 2006 9:37 am 
Offline
Breakbeat Nuttzer
User avatar

Joined: Wed Mar 24, 2004 8:57 am
Posts: 13098
Location: Melbourne, Australia


Last edited by Weirdan on Sun Feb 22, 2009 10:45 am, edited 3 times in total.
removed syntax highlighting so parser won't eat entire code block


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 06, 2006 9:38 am 
Offline
Breakbeat Nuttzer
User avatar

Joined: Wed Mar 24, 2004 8:57 am
Posts: 13098
Location: Melbourne, Australia


Top
 Profile  
 
 Post subject:
PostPosted: Sat Apr 07, 2007 1:36 pm 
Offline
Forum Contributor

Joined: Fri Mar 23, 2007 3:04 pm
Posts: 205
How do you use this code? it's pretty good. i copied the smilies. but after that what should i do to use your bbcode parser


Top
 Profile  
 
 Post subject: Re: Simple BBTag Parser
PostPosted: Wed Jun 25, 2008 10:08 am 
Offline
Forum Newbie

Joined: Wed May 14, 2008 11:14 am
Posts: 23
Never used it but I know Pear has something that does something similar: http://pear.php.net/package/HTML_BBCodeParser


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 21 posts ]  Go to page 1, 2  Next

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron
Powered by phpBB® Forum Software © phpBB Group