Skip to content

Another BBCode Helper

World Wide Web Server edited this page Jul 4, 2012 · 30 revisions

Category:Helpers

I wanted a bbCode helper similar to the original smiley helper (wich is so usefull) but i couldn't find it. This is my first Ignited code and i hope it will help someone. Remarks are welcome on the forum topic.

This helper can actualy :

  • Generate a javascript function needed to insert bbCodes into a form field
  • Parse bbCode
  • Clear bbCode tags
  • Generate an array of bbCode buttons that can be clicked to be inserted

[code]<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /**

// ------------------------------------------------------------------------

/**

  • CodeIgniter bbCode Helpers
  • @package CodeIgniter
  • @subpackage Helpers
  • @category Helpers
  • @author Santoni Jean-André */

// ------------------------------------------------------------------------

/**

  • JS Insert bbCode
  • Generates the javascrip function needed to insert bbcodes into a form field
  • @access public
  • @param string form name
  • @param string field name
  • @return string */

function js_insert_bbcode($form_name = '', $form_field = '') { ?> <script type="text/javascript"> function insert_bbcode(bbopen, bbclose) { var input = window.document.<?=$form_name.'.'.$form_field; ?>; input.focus();

    /* for Internet Explorer )*/
    if(typeof document.selection != 'undefined')
    {
        var range = document.selection.createRange();
        var insText = range.text;
        range.text = bbopen + insText + bbclose;
        range = document.selection.createRange();
        if (insText.length == 0)
        {
            range.move('character', -bbclose.length);
        }
        else
        {
            range.moveStart('character', bbopen.length + insText.length + bbclose.length);
        }
        range.select();
    }
    
    /* for newer browsers like Firefox */

    else if(typeof input.selectionStart != 'undefined')
    {
        var start = input.selectionStart;
        var end = input.selectionEnd;
        var insText = input.value.substring(start, end);
        input.value = input.value.substr(0, start) + bbopen + insText + bbclose + input.value.substr(end);
        var pos;
        if (insText.length == 0)
        {
            pos = start + bbopen.length;
        }
        else
        {
            pos = start + bbopen.length + insText.length + bbclose.length;
        }
        input.selectionStart = pos;
        input.selectionEnd = pos;
    }    

    /* for other browsers like Netscape... */
    else
    {
        var pos;
        var re = new RegExp('^[0-9]{0,3}$');
        while(!re.test(pos))
        {
            pos = prompt("insertion (0.." + input.value.length + "):", "0");
        }
        if(pos > input.value.length)
        {
            pos = input.value.length;
        }
        var insText = prompt("Please tape your text");
        input.value = input.value.substr(0, pos) + bbopen + insText + bbclose + input.value.substr(pos);
    }
} 
&lt;/script&gt; 
&lt;?php 

}

// ------------------------------------------------------------------------

/**

  • Parse bbCode

  • Takes a string as input and replace bbCode by (x)HTML tags

  • @access public

  • @param string the text to be parsed

  • @return string

*/

function parse_bbcode($t, $bbcode_to_parse = NULL)

{

if ( ! is_array($bbcode_to_parse))

{

    if (FALSE === ($bbcode_to_parse = _get_bbcode_to_parse_array()))

    {

        return FALSE;

    }        

}



foreach ($bbcode_to_parse as $key => $val)

{        
    for ($i = 1; $i <= $bbcode_to_parse[$key][3]; $i++) // loop for imbricated tags
    {
        if ($bbcode_to_parse[$key][0] == "str")
        {
            $t = str_replace($key, $bbcode_to_parse[$key][1], $t);
        }
        elseif ($bbcode_to_parse[$key][0] == "ereg")
        {
            if (ereg($key, $t))
            $t = ereg_replace($key, $bbcode_to_parse[$key][1], $t);
        }
    }
}



return $t;

}

// ------------------------------------------------------------------------

/**

  • Clear bbCode

  • Takes a string as input and remove bbCode tags

  • @access public

  • @param string the text to be parsed

  • @return string

*/
function clear_bbcode($t, $bbcode_to_parse = NULL)

{

if ( ! is_array($bbcode_to_parse))

{

    if (FALSE === ($bbcode_to_parse = _get_bbcode_to_parse_array()))

    {

        return FALSE;

    }        

}



foreach ($bbcode_to_parse as $key => $val)

{        
    for ($i = 1; $i <= $bbcode_to_parse[$key][3]; $i++) // loop for imbricated tags
    {
        if ($bbcode_to_parse[$key][0] == "str")
        {
            $t = str_replace($key, $bbcode_to_parse[$key][2], $t);
        }
        elseif ($bbcode_to_parse[$key][0] == "ereg")
        {
            if (ereg($key, $t))
            $t = ereg_replace($key, $bbcode_to_parse[$key][2], $t);
        }
    }
}



return $t;

}

// ------------------------------------------------------------------------

/**

  • Get bbCode Buttons
  • Returns an array of bbcode buttons that can be clicked to be inserted
  • into a form field.
  • @access public
  • @return array */

function get_bbcode_buttons($bbcode = NULL) { if ( ! is_array($bbcode)) { if (FALSE === ($bbcode = _get_bbcode_array())) { return $str; }
}

foreach ($bbcode as $key => $val)
{
    $button[] = '&lt;input type="button" class="button" id="'.$key.'" name="'.$key.'" value="'.$key.'" onClick="'.$val.'" /&gt;';
}

return $button;

}

// ------------------------------------------------------------------------

/**

  • Get bbCode Array

  • Fetches the config/bbcode.php file

  • @access private

  • @return mixed */
    function _get_bbcode_array() { if ( ! file_exists(APPPATH.'config/bbcode'.EXT)) { return FALSE; }

    include(APPPATH.'config/bbcode'.EXT);

    if ( ! isset($bbcode) OR ! is_array($bbcode)) { return FALSE; }

    return $bbcode; }

// ------------------------------------------------------------------------

/**

  • Get bbCode Array for parsing

  • Fetches the config/bbcode.php file

  • @access private

  • @return mixed

*/

function _get_bbcode_to_parse_array()

{

if ( ! file_exists(APPPATH.'config/bbcode'.EXT))

{

    return FALSE;

}



include(APPPATH.'config/bbcode'.EXT);



if ( ! isset($bbcode_to_parse) OR ! is_array($bbcode_to_parse))

{

    return FALSE;

}



return $bbcode_to_parse;

}

?>[/code]

And here is the config/bbcode.php file :

[code]<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
BBCODE
-------------------------------------------------------------------
This file contains two arrays of bbcode for use with the bbcode helper.
The first array is for buttons and the second is for parsing.

| */

$bbcode = array(

// name onClick

"b"            =>        "[removed]insert_bbcode('[b]', '[/b]');return(false)",
"i"            =>        "[removed]insert_bbcode('[i]', '[/i]');return(false)",
"u"            =>        "[removed]insert_bbcode('[u]', '[/u]');return(false)",
"center"       =>        "[removed]insert_bbcode('[center]', '[/center]');return(false)",
"right"        =>        "[removed]insert_bbcode('[right]', '[/right]');return(false)",
"justify"      =>        "[removed]insert_bbcode('[justify]', '[/justify]');return(false)",
"quote"        =>        "[removed]insert_bbcode('[q=AUTHOR]', '[/q]');return(false)",
"img"          =>        "[removed]insert_bbcode('[img]', '[/img]');return(false)",
"url"          =>        "[removed]insert_bbcode('[url=]', '[/url]');return(false)",
"email"        =>        "[removed]insert_bbcode('[email=]', '[/email]');return(false)"
    );

$bbcode_to_parse = array(

// tag type replacement clean loop

"[base_url]"                                                =>        array("str",    base_url(),                                   base_url(),        1),
"[/]"                                                       =>        array("str",    "<hr width=\"100%\" size=\"1\" />",           "",                1),
"[hr]"                                                      =>        array("str",    "<hr width=\"100%\" size=\"1\" />",           "",                1),
"[b]"                                                       =>        array("str",    "<strong>",                                   "",                1),
"[/b]"                                                      =>        array("str",    "</strong>",                                  "",                1),
"[i]"                                                       =>        array("str",    "<em>",                                       "",                1),
"[/i]"                                                      =>        array("str",    "</em>",                                      "",                1),
"[u]"                                                       =>        array("str",    "<u>",                                        "",                1),
"[/u]"                                                      =>        array("str",    "</u>",                                       "",                1),
"[center]"                                                  =>        array("str",    "<div style=\"text-align: center\">",         "",                1),
"[/center]"                                                 =>        array("str",    "</div>",                                     "",                1),
"[right]"                                                   =>        array("str",    "<div style=\"text-align: right\">",          "",                1),
"[/right]"                                                  =>        array("str",    "</div>",                                     "",                1),
"[justify]"                                                 =>        array("str",    "<div style=\"text-align: justify\">",        "",                1),
"[/justify]"                                                =>        array("str",    "</div>",                                     "",                1),
"\[color= ?(([[:alpha:]]+)|(#[[:digit:][:alpha:]]{6})) ?\]" =>        array("ereg",   "<span style=\"color: \\1\">",                "",                1),
"[/color]"                                                  =>        array("str",    "</span>",                                    "",                1),
"\[size= ?([[:digit:]]+) ?\]"                               =>        array("ereg",   "<span style=\"font-size: \\1px\">",          "",                1),
"[/size]"                                                   =>        array("str",    "</span>",                                    "",                1),
"\[email\] ?([^\[]*) ?\[/email\]"                           =>        array("ereg",   "<a href=\"mailto:\\1\">\\1</a>",             "(\\1)",           1),
"\[email ?=([^\[]*) ?] ?([^]]*) ?\[/email\]"                =>        array("ereg",   "<a href=\"mailto:\\1\">\\2</a>",             "\\2 (\\1)",       1),
"\[img\] ?([^\[]*) ?\[/img\]"                               =>        array("ereg",   "<img src=\"\\1\" alt=\"\" border=\"0\" />",  "",                1),
"\[img ?= ?([^\[]*) ?\]"                                    =>        array("ereg",   "<img src=\"\\1\" alt=\"\" border=\"0\" />",  "",                1),
"[list]"                                                    =>        array("str",    "<ul>",                                       "\n",              1),
"[/list]"                                                   =>        array("str",    "</ul>",                                      "\n",              1),
"[*]"                                                       =>        array("str",    "<li>",                                       " - ",             1),
"[/*]"                                                      =>        array("str",    "</li>",                                      "\n",              1),
"\[url\] ?([^\[]*) ?\[/url\]"                               =>        array("ereg",   "<a href=\"\\1\">\\1</a>",                    "(\\1)",           1),
"\[url ?=([^\[]*) ?] ?([^]]*) ?\[/url\]"                    =>        array("ereg",   "<a href=\"\\1\" target=\"_blank\">\\2</a>",  "\\2 (\\1)",       1),
"\[URL\] ?([^\[]*) ?\[/URL\]"                               =>        array("ereg",   "<a href=\"\\1\">\\1</a>",                    "(\\1)",           1),
"\[URL ?=([^\[]*) ?] ?([^]]*) ?\[/URL\]"                    =>        array("ereg",   "<a href=\"\\1\" target=\"_blank\">\\2</a>",  "\\2 (\\1)",       1),
"\[q\] ?([^\[]*) ?\[/q\]"                                   =>        array("ereg",   "<blockquote>\\1</blockquote>",               "\"\\1\"",         5),
"\[q ?=([^\[]*) ?] ?([^]]*) ?\[/q\]"                        =>        array("ereg",   "<blockquote cite=\"\\1\">\\2</blockquote>",  "\"\\2\" (\\1)",   5)
    );

?>[/code]

Clone this wiki locally