Към съдържанието

BBcode Editor и Parser

  • plamba95
  • 12 072 прочитания

Урокът е от архива на сайта и е писан преди години. Някои бутони и менюта в програмите вече може да изглеждат различно.

Втората версия на урока за bbcode editor и parser с добавени нови функционалности и оптимизиран код!

Мисля, че е време да ви представя и втората версия на bbcode editor и parser! Тук всичко е написано на jQuery(което прави и библиотеката задължителна). Има и нови функции за offtopic, клипове от vbox7.com и youtube.com, оцветяване на кода(благодарение на prettify). Също така използвам и Алтернативи на alert,confirm и prompt v2 вместо стандартните prompt,confirm и alert функции. Има и други новости, но тях ги оставам на вас да ги разучите :)
За да не трупаме урока с излишни редове си изтеглете prettify и Алтернативи на alert,confirm и prompt v2 . А тук ще ви представя само файловете за самия скрипт за bbcode editor и parser!

bbcode.js

$.fn.bbcodetoolbar = function(data) { //създаваме функцията за показване на bbcode editor-a
    var i = $('.toolbar').length;
    if ($('.toolbar#tool' + i).is(':visible')) {
        i++;
    }
	var $this = $(this);

	var def_data = {
        'b' : false,       
		'i' : false,
		'u' : false,
		's' : false,
		'l' : false,
		'c' : false,
		'r' : false,
		'j' : false,
		'list' : false,
		'url' : false,
		'img' : false,
		'imgUrl' : false,
		'code' : false,
		'quote' : false,
		'offtopic' : false,
		'player' : false,
		'fontcolor' : false,
		'fontsize' : false,
		'table' : false,
		'emoticons' : false
    };

    if (data) {
		var show=[];
		datata = data.split(',');
		for (var val in def_data) {
			show[val] = false;
        }   		
		$.each(datata,function(i,v) {
			show[v] = true;
		});
    }   
	else {
		var show=[];
		for (var val in def_data) {
			show[val] = true;
        }
	}
	$('body').on('click', '.toolbar#tool' + i +' > .button', function() {
        var alt = $(this).attr('alt');
        $this.addTags('[' + alt + ']', '[/' + alt + ']');
    });
    $('body').on("change", '.toolbar#tool' + i +' > .fontcolor', function() {
        $this.addTags('[color=' + $(this).val() + ']', '[/color]');
    });
    $('body').on("change", '.toolbar#tool' + i +' > .fontsize', function() {
        $this.addTags('[size=' + $(this).val() + ']', '[/size]');
    });
    $('body').on('click', '.toolbar#tool' + i +' > .unList', function() {
        $this.addTags("[list=un]n[*]","[/*]n[/list]");
    });
    $('body').on('click', '.toolbar#tool' + i +' > .orList', function() {
        $this.addTags("[list=or]n[*]","[/*]n[/list]");
    });
	$('body').on('click', '.toolbar#tool' + i +' > .listItem', function() {
        $this.addTags("n[*]","[/*]");
    });
    $('body').on('click', '.toolbar#tool' + i +' > .addTable', function() {
        $this.addTable();
    });
    $('body').on('click', '.toolbar#tool' + i +' > .btnPicture', function() {
        $this.addImage();
    });
    $('body').on('click', '.toolbar#tool' + i +' > .btnLink', function() {
        $this.addUrl();
    });
    $('body').on('click', '.toolbar#tool' + i +' > .btnLinkPicture', function() {
        $this.addImgUrl();
    });
    $('body').on('click', '.toolbar#tool' + i +' > .vbox7, .toolbar#tool' + i +' > .youtube', function() {
		var site = $(this).attr('class').split(' ')[1];
        $this.addPlayer(site);
    });	
    $('body').on('click', '.toolbar#tool' + i +' > .showSmiles', function() {
        $this.showSmiles();
    });
    $('body').on('click', '.toolbar#tool' + i +' > .smiles > .emotions', function() {
        var alt = $(this).attr('alt');
        $this.addTags('', ' ' + alt + ' ');
    });	

	var tools = "";
    tools += "<div class="toolbar" id="tool" + i + "">";
    if(show['b']) tools += "<img class="button" src="images/bold.gif" alt="b" title="Удебеленяване" />";
    if(show['i']) tools += "<img class="button" src="images/italic.gif" alt="i" title="Наклоняване" />";
    if(show['u'])  tools += "<img class="button" src="images/underline.gif" alt="u" title="Подчертаване"/>";
    if(show['s'])  tools += "<img class="button" src="images/strike.gif" alt="s" title="Зачеркване"/>";
    if(show['l']) tools += "<img class="button" src="images/left.png" alt="l" title="Подравняване в ляво"/>";
    if(show['c']) tools += "<img class="button" src="images/center.png" alt="c" title="Подравняване в центъра"/>";
    if(show['r']) tools += "<img class="button" src="images/right.png" alt="r" title="Подравняване в дясно"/>";
    if(show['j']) tools += "<img class="button" src="images/justify.png" alt="j" title="Двостранно подравняване"/>";
    if(show['list']) {
		tools += "<img class="function unList" src="images/unordered.gif" title="Списък"/>";
		tools += "<img class="function orList" src="images/ordered.gif" title="Списък с номерация"/>";
		tools += "<img class="function listItem" src="images/listItem.gif" title="Елемент на списък"/>";
	}
    if(show['url']) tools += "<img class="function btnLink" src="images/link.gif" title="Добави линк"/>";
    if(show['img']) tools += "<img class="function btnPicture" src="images/picture.gif" title="Добави снимка"/>";
    if(show['imgUrl']) tools += "<img class="function btnLinkPicture" src="images/linkpic.gif" title="Добави снимка с линк"/>";
    if(show['quote']) tools += "<img class="button" src="images/quote.gif" alt="quote" title="Цитат"/>";
    if(show['code']) tools += "<img class="button" src="images/code.gif" alt="code" title="Код"/>";
    if(show['offtopic']) tools += "<img class="button" src="images/offtopic.gif" alt="offtopic" title="Извън темата"/>";

    if(show['player']) {
		tools += "<img class="function vbox7" src="images/vbox.png" id="vbox7" title="vbox7"/>";
		tools += "<img class="function youtube" src="images/youtube.jpg" id="youtube" title="youtube"/>";
	}
    if(show['fontcolor']) {tools += "<br /><select name="fontcolor" class="fontcolor">";
		tools += "<option value="0" style="color:black">Изберете цвят</option>";
		tools += "<option value="black" style="color:black">Черенo</option>";
		tools += "<option value="silver" style="color:silver">Сребро</option>";
		tools += "<option value="gray" style="color:gray">Сиво</option>";
		tools += "<option value="maroon" style="color:maroon">Кестеняво</option>";
		tools += "<option value="red" style="color:red">Червено</option>";
		tools += "<option value="navy" style="color:navy">Тъмносиньо</option>";
		tools += "<option value="blue" style="color:blue">Синьо</option>";
		tools += "<option value="green" style="color:green">Зелено</option>";
		tools += "<option value="olive" style="color:olive">Маслиненозелено</option>";
		tools += "<option value="yellow" style="color:yellow;background-color:red;">Жълто</option>";
		tools += "<option value="white" style="color:white;background-color:#ADADAD;">Бяло</option>";
		tools += "<option value="purple" style="color:purple">Пурпурен</option>";
		tools += "</select>";
	}
    if(show['fontsize']) {
		tools += "<select name="fontsize" class="fontsize">";
		tools += "<option value="0">Изберете размер</option>";
		tools += "<option value="7">Много малък</option>";
		tools += "<option value="9">Малък</option>";
		tools += "<option value="12">Нормален</option>";
		tools += "<option value="18">Голям</option>";
		tools += "<option value="24">Много голям</option>";
		tools += "</select>";
	}
    if(show['table']) {
		tools += "Колони: <input type='text' name='tbcols' class='tbcols' size='1' maxlength='2'/>";
		tools += "Редове: <input type='text' name='tbrows' class='tbrows' size='1' maxlength='2'/>";
		tools += "<input type='button' name='addTable' class='addTable' value='Добави таблица'/>";
	}
	if(show['emoticons']) tools += "<input type='button' class='showSmiles' value='Емотикони'/><div class='smiles'></div><br />"; //ако не искате да имате smiles махнете този ред!
    tools += "</div>";
    $this.before(tools);
	$this.appendTo('.toolbar#tool' + i);
    var dir = "smiles/"; //въведи папката в която са картинките
	var title = "";
    var link = ['smile.gif', 'sad.gif', 'laught.gif', 'bleh.gif', 'shy.gif', 'cool.gif', 'love.gif', 'angel.gif', 'bye.gif', 'thumbsup.gif', 'chin.gif', 'bop.gif',
            'crazy.gif', 'mad.gif', 'spock.gif', 'explode.gif', 'drool.gif', 'popcorn.gif', 'icecream.gif', 'arms.gif', 'baby.gif', 'badday.gif', 'bananadance.gif',
            'banned.gif', 'bash.gif', 'beer.gif', 'beer2.gif', 'biggrin.gif', 'blink.gif', 'bouncy.gif', 'bow.gif', 'cake.gif', 'chair.gif', 'cheekkiss.gif', 'cigar.gif',
            'clap.gif', 'clover.gif', 'clown.gif', 'confused.gif', 'console.gif', 'cry.gif', 'cry2.gif', 'cupid.gif', 'drinks.gif', 'dry.gif', 'dumbells.gif', 'dunce.gif',
            'evil.gif', 'evilmad.gif', 'excited.gif', 'fart.gif', 'fish.gif', 'fishing.gif', 'flowers.gif', 'gathering.gif', 'goodgrief.gif', 'greedy.gif', 'group.gif',
            'guns.gif', 'happy.gif', 'happy2.gif', 'happyno.gif', 'happyyes.gif', 'hbd.gif', 'hooray.gif', 'horse.gif', 'hug.gif', 'huglove.gif', 'hump.gif', 'jawdrop.gif',
            'kissing.gif', 'kissing2.gif', 'lol.gif', 'look.gif', 'lovers.gif', 'music.gif', 'no.gif', 'ohmy.gif', 'ouch.gif', 'poke.gif', 'puke.gif', 'rant.gif', 'rant2.gif',
            'rofl.gif', 'rolleyes.gif', 'shoot.gif', 'shoot2.gif', 'shutup.gif', 'sick.gif', 'slaphead.gif', 'sleep.gif', 'sleeping.gif', 'smartass.gif', 'snap.gif',
            'stamp.gif', 'stereo.gif', 'strongbench.gif', 'tears.gif', 'tease.gif', 'therethere.gif', 'thumbsdown.gif', 'unsure.gif', 'wavecry.gif', 'weakbench.gif', 'weirdo.gif',
            'what.gif', 'whip.gif', 'whistle.gif', 'wiggle.gif', 'wink.gif', 'worthy.gif', 'wub.gif', 'yawn.gif', 'yikes.gif']; //въведи името на всяка една картинка
    var icon = [':)', ':(', ':D', ':P', '(shy)', '8)', '(h)', '(angel)', '(bye)', '(thumbsup)', '(chin)', '(bop)', '(crazy)', '(mad)', '(spock)', ':@', '(drool)',
            '(popcorn)', '(icecream)', '(arms)', '(baby)', '(badday)', '(bananadance)', '(banned)', '(bash)', '(beer)', '(beer2)', '(biggrin)', '(blink)', '(bouncy)', '(bow)', '(cake)',
            '(chair)', '(cheekkiss)', '(cigar)', '(clap)', '(clover)', '(clown)', '(confused)', '(console)', ';(', ':S', '(cupid)', '(drinks)', '(dry)', '(dumbells)', '(dunce)',
            '(evil)', '(evilmad)', '(excited)', '(fart)', '(fish)', '(fishing)', '(flowers)', '(gathering)', '(goodgrief)', '(greedy)', '(group)', '(guns)', '(happy)', '(happy2)',
            '(happyno)', '(happyyes)', '(hbd)', '(hooray)', '(horse)', '(hug)', '(huglove)', '(hump)', '(jawdrop)', ':*', '(kissing2)', '(lol)', '(look)', '(lovers)', '(music)', '(no)',
            '(ohmy)', '(ouch)', '(poke)', '(puke)', '(rant)', '(rant2)', '(rofl)', '(rolleyes)', '(shoot)', '(shoot2)', ':X', '(sick)', '(slaphead)', '(sleep)', '(sleeping)',
            '(smartass)', '(snap)', '(stamp)', '(stereo)', '(strongbench)', '(tears)', '(tease)', '(therethere)', '(thumbsdown)', '(unsure)', '(wavecry)', '(weakbench)', '(weirdo)',
            '(what)', '(whip)', '(whistle)', '(wiggle)', ';)', '(worthy)', '(wub)', '(yawn)', '(yikes)'];  //въведи съответния текст(иконката) който ще се добавя в textarea-та

    jQuery.each(link, function(i, v) { //за всяки веведен линк...
        var cont = $('.smiles').html();
		title = v.split('.')[0];
        $('.smiles').html(cont + "<img src='" + dir + v + "' class="emotions" title=""+title+"" alt="" + icon[i] + ""/> "); //... ще се добавя нов img над textareata
    });
}
$.fn.checkSelect = function() { //функция проверяваща дали има селектиран текст
    var $this = $(this);
    var len = $this.val().length;
    var start = $this[0].selectionStart;
    var end = $this[0].selectionEnd;
    var selectedText = $this.val().substring(start, end);
    if (selectedText) return selectedText;
    else return false;
}

$.fn.selectRange = function(start, end) {//функция преместваща курсора
    return this.each(function() {
        if (this.setSelectionRange) {	
            this.focus();
            this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
			range.moveStart('character', start);
            range.moveEnd('character', end);            
            range.select();
        }
    });
}

$.fn.showSmiles = function() { //функция за показване на списъка с емотиконките
    $this = $(this);
	$the = $this.parents('.toolbar');
    $the.find('.smiles').stop();
    var position = $the.find('.showSmiles').position();
	var widthsh = $the.find('.showSmiles').width();
    var height = $the.find('.showSmiles').height()+7;
    var width = $the.find('.smiles').width() / 2;
    $the.find('.smiles').css({
        left: position.left - width + widthsh,
        top: position.top + height
    });
    if (!$the.find('.smiles').is(':visible')) $the.find('.smiles').slideDown('fast');
    var mouse_is_inside = false;
    $('.smiles').hover(function() {
        mouse_is_inside = true;
    }, function() {
        mouse_is_inside = false;
    });
    $("body").mouseup(function() {
        if (!mouse_is_inside) $the.find('.smiles').slideUp('fast');
    });
}

$.fn.addTags = function(openTag, closeTag) { //функция за добавяне на тагове
    if (closeTag == "[/color]" || closeTag == "[/size]") {
        $("option[value='0']").attr('selected', 'selected');
    } //ако таг2 е [/color] или [/size] при изпълнение на функцията ще се селектне отново първия option
    var $this = $(this);	
	var select = $this.checkSelect();
    var scrollTop = $this.scrollTop;
    var scrollLeft = $this.scrollLeft;
    var len = $this.val().length;
    var start = $this[0].selectionStart;
    var end = $this[0].selectionEnd;
    var selectedText = $this.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    $this.val($this.val().substring(0, start) + replacement + $this.val().substring(end, len));
    $this.scrollTop = scrollTop;
    $this.scrollLeft = scrollLeft;
	var oplen = (openTag != "") ? openTag.length+start : closeTag.length+end ;
	var cllen = closeTag.length+end;
	if(select) $this.selectRange(end+cllen,end+cllen);
	else $this.selectRange(oplen,oplen);
}

$.fn.addPlayer = function(site) {//функция за добавяне на плеъра от vbox7.com или youtube.com
    $this = $(this);
    var select = $this.checkSelect();
    var text;
    if (select) {
		if(select.indexOf(site+'.com') > -1) $this.addTags("[" + site + "]", "[/" + site + "]");    
	}
    else {
        jqcustom('Въведете линк от <a href="http://' + site + '.com" target="_blank">http://' + site + '.com</a>', {
            'type': 'prompt',
            'title': 'Добавяне на player',
            'ok': 'Готово',
            'cancel': 'Отказ',
            'value': 'http://'
        }, function(url) {
            if (url && url != 'http://' && url.indexOf(site+'.com') > -1 ) {
                text = "[" + site + "]" + url + "[/" + site + "]";
                $this.addTags('', text);
            }
        });
    }
}

$.fn.addTable = function() { //функция за създаване на таблица    
    var $this = $(this); //взимаме id-то на textarea-та
	$the = $this.parents('.toolbar');
    var rows = $the.find('.tbrows').val(); //стойноста на input rows т.е колко реда да има таблицата
    var cols = $the.find('.tbcols').val(); //стойноста на input cols т.е колко колони да има таблицата
    var text = "n[table]n";
    for (i = 1; i <= rows; i++) { //за всяки ред добавяме код за редове
        text += "[tr]n";
        for (k = 1; k <= cols; k++) { //за всяки колона добавяме код за колона
            text += "[td]";
            text += "[/td]n";
        }
        text += "[/tr]n";
    }
    text += "[/table]n";
    if (cols > 0 && rows > 0) $this.addTags('', text); //добавяме таблицата към textarea-та
    $the.find('.tbrows').val("");
    $the.find('.tbcols').val(""); //изчистваме 2-та input-а
}

$.fn.addImage = function() { //функция за добавяне на снимка
    $this = $(this);
    var text;
    var select = $this.checkSelect();
    if (select) {
        $this.addTags('[img]', '[/img]');
    } else {
        jqcustom('Въведи линк към картинката', {
            'type': 'prompt',
            'title': 'Добавяне на картинката',
            'ok': 'Готово',
            'cancel': 'Отказ',
            'value': 'http://'
        }, function(url) {
            if (url && url != 'http://') {
                text = '[img]' + url + '[/img]';
                $this.addTags('', text);
            }
        });
    }
}

$.fn.addUrl = function() { //функция за добавяне на линк
    $this = $(this);
    var text;
    var select = $this.checkSelect();
    jqcustom('Въведете линк', {
        'type': 'prompt',
        'title': 'Добавяне на линк',
        'ok': 'Готово',
        'cancel': 'Отказ',
        'value': 'http://'
    }, function(url) {
        if (url && url != 'http://') {
            if (select) {
                $this.addTags('[url=' + url + ']', '[/url]');
            } else {
                jqcustom('Въведете име на линка', {
                    'type': 'prompt',
                    'title': 'Добавяне на линк',
                    'ok': 'Готово',
                    'cancel': 'Отказ'
                }, function(url2) {
                    url2 = (url2) ? url2 : "link";
                    text = '[url=' + url + ']' + url2 + '[/url]';
                    $this.addTags('', text);
                });
            }
        }
    });
}

$.fn.addImgUrl = function() { //функция за добавяне на снимка с линк
    $this = $(this);
    var text;
    var select = $this.checkSelect();
    jqcustom('Въведете линк', {
        'type': 'prompt',
        'title': 'Добавяне на линк с картинка',
        'ok': 'Готово',
        'cancel': 'Отказ',
        'value': 'http://'
    }, function(url) {
        if (url && url != 'http://') {
            if (select) {
                $this.addTags('[img=' + url + ']', '[/img]');
            } else {
                jqcustom('Въведи линк към картинката', {
                    'type': 'prompt',
                    'title': 'Добавяне на линк с картинка',
                    'ok': 'Готово',
                    'cancel': 'Отказ',
                    'value': 'http://'
                }, function(url2) {
                    if (url2 && url2 != 'http://') {
                        text = '[img=' + url + ']' + url2 + '[/img]';
                        $this.addTags('', text);
                    }
                });
            }
        }
    });
}

$(function() {
	$(".showoff").click(function() { //скрипт за показване съдържанието на offtopic
		$(this).parents(".offtable").find(".offtopic").toggle();
	});
});
bbcode.css
.button,.function {
    border: 1px solid
	#ccc;margin: 1px;
	padding: 2px;
}

.button:hover,.function:hover {
    filter: progid: DXImageTransform.Microsoft.Alpha(opacity = 60);
	-moz-opacity: 0.6;
	opacity: 0.6;
}

.smiles {
    border: black 1px solid;
	display: none;
	position: absolute;
	background: #b7b8ba;
	width: 600px ;
}
.smiles img {
	cursor: pointer;
}

.code {
	border:solid 1px black;
	width:90%;
}

.quote {
	background-color:#C7C7C7;
	border:solid 1px black;
	width:90%;
}

.offtopic {
	width:90%;
	display:none;
	background-color:#C7C7C7;
	border:solid 1px black;
}
bbcode.php
<?php
function bbcode($text) {		
    $text = preg_replace("/[b](.+?)[/b]/is", '<b>$1</b>', $text); //заменяме bbcode [b]текст[/b] с html-а <b>текст</b>... надолу се прави абсолютно същотото за всеки bbcode

    $text = preg_replace("/[i](.+?)[/i]/is", '<i>$1</i>', $text);

    $text = preg_replace("/[u](.+?)[/u]/is", '<u>$1</u>', $text);

    $text = preg_replace("/[l](.+?)[/l]/is",
        '<div style="text-align:left;">$1</div>', $text);

    $text = preg_replace("/[c](.+?)[/c]/is",
        '<div style="text-align:center;">$1</div>', $text);

    $text = preg_replace("/[r](.+?)[/r]/is",
        '<div style="text-align:right;">$1</div>', $text);

    $text = preg_replace("/[j](.+?)[/j]/is",
        '<div style="text-align:justify;">$1</div>', $text);

    $text = preg_replace("/[s](.+?)[/s]/is", '<strike>$1</strike>', $text);   

    $patterns = array('
						/[url=(.*?)](.*?)[/url]/is', 
						'/[img=(.*?)](.*?)[/img]/is',
						'/[url](.*?)[/url]/is', 
						'/[img](.*?)[/img]/is', 
						'/(^(http|https)(S+))/is'
					);
    $replaces = array('<a href="$1" target="_blank">$2</a>',
        '<a href="$1" target="_blank"><img src="$2" target="_blank"/></a>',
        '<a href="$1" target="_blank">$1</a>', '<img src="$1" target="_blank"/>',
        '<a href="$1" target="_blank">$1</a>');

    $text = preg_replace($patterns, $replaces, $text);

    $text = preg_replace("/[list=un](.+?)[/list]/is", '<ul>$1</ul>', $text);

    $text = preg_replace("/[list=or](.+?)[/list]/is", '<ol>$1</ol>', $text);

    $text = preg_replace("/[*](.+?)[/*]/is", '<li>$1</li>', $text);

    $text = preg_replace("/[quote](.+?)[/quote]/is",
        '<table cellspacing="1" border="0"><tr><td class="quote">Цитат:</td></tr><tr><td>$1</td></tr></table>',
        $text);

    $text = preg_replace("/[quote=(.+?)](.+?)[/quote]/is",
        '<table cellspacing="1" border="0"><tr><td class="quote">$1 каза:</td></tr><tr><td>$2</td></tr></table>',
        $text);

    $text = preg_replace("/[color=(.+?)](.+?)[/color]/is",
        '<span style="color:$1">$2</span>', $text);

    $text = preg_replace("/[size=(.+?)](.+?)[/size]/is",
        '<span style="font-size:$1px;">$2</span>', $text);

    $text = preg_replace("/[code](.+?)[/code]/is",
        '<table cellspacing="1" border="0"><tr><td>Code:</td></tr><tr><td class="code"><code class="prettyprint">$1</code></td></tr></table>',
        $text);

    $dir = "smiles"; //папката в която са картинките
    $smiles = array(':)', ':(', ':D', ':P', '(shy)', '8)', '(h)', '(angel)', '(bye)',
        '(thumbsup)', '(chin)', '(bop)', '(crazy)', '(mad)', '(spock)', ':@', '(drool)',
        '(popcorn)', '(icecream)', '(arms)', '(baby)', '(badday)', '(bananadance)',
        '(banned)', '(bash)', '(beer)', '(beer2)', '(biggrin)', '(blink)', '(bouncy)',
        '(bow)', '(cake)', '(chair)', '(cheekkiss)', '(cigar)', '(clap)', '(clover)',
        '(clown)', '(confused)', '(console)', ';(', ':S', '(cupid)', '(drinks)', '(dry)',
        '(dumbells)', '(dunce)', '(evil)', '(evilmad)', '(excited)', '(fart)', '(fish)',
        '(fishing)', '(flowers)', '(gathering)', '(goodgrief)', '(greedy)', '(group)',
        '(guns)', '(happy)', '(happy2)', '(happyno)', '(happyyes)', '(hbd)', '(hooray)',
        '(horse)', '(hug)', '(huglove)', '(hump)', '(jawdrop)', ':*', '(kissing2)',
        '(lol)', '(look)', '(lovers)', '(music)', '(no)', '(ohmy)', '(ouch)', '(poke)',
        '(puke)', '(rant)', '(rant2)', '(rofl)', '(rolleyes)', '(shoot)', '(shoot2)',
        ':X', '(sick)', '(slaphead)', '(sleep)', '(sleeping)', '(smartass)', '(snap)',
        '(stamp)', '(stereo)', '(strongbench)', '(tears)', '(tease)', '(therethere)',
        '(thumbsdown)', '(unsure)', '(wavecry)', '(weakbench)', '(weirdo)', '(what)',
        '(whip)', '(whistle)', '(wiggle)', ';)', '(worthy)', '(wub)', '(yawn)',
        '(yikes)'); //текста който е бил в textarea-та
    $smileslink = array('smile.gif', 'sad.gif', 'laught.gif', 'bleh.gif', 'shy.gif',
        'cool.gif', 'love.gif', 'angel.gif', 'bye.gif', 'thumbsup.gif', 'chin.gif',
        'bop.gif', 'crazy.gif', 'mad.gif', 'spock.gif', 'explode.gif', 'drool.gif',
        'popcorn.gif', 'icecream.gif', 'arms.gif', 'baby.gif', 'badday.gif',
        'bananadance.gif', 'banned.gif', 'bash.gif', 'beer.gif', 'beer2.gif',
        'biggrin.gif', 'blink.gif', 'bouncy.gif', 'bow.gif', 'cake.gif', 'chair.gif',
        'cheekkiss.gif', 'cigar.gif', 'clap.gif', 'clover.gif', 'clown.gif',
        'confused.gif', 'console.gif', 'cry.gif', 'cry2.gif', 'cupid.gif', 'drinks.gif',
        'dry.gif', 'dumbells.gif', 'dunce.gif', 'evil.gif', 'evilmad.gif', 'excited.gif',
        'fart.gif', 'fish.gif', 'fishing.gif', 'flowers.gif', 'gathering.gif',
        'goodgrief.gif', 'greedy.gif', 'group.gif', 'guns.gif', 'happy.gif',
        'happy2.gif', 'happyno.gif', 'happyyes.gif', 'hbd.gif', 'hooray.gif',
        'horse.gif', 'hug.gif', 'huglove.gif', 'hump.gif', 'jawdrop.gif', 'kissing.gif',
        'kissing2.gif', 'lol.gif', 'look.gif', 'lovers.gif', 'music.gif', 'no.gif',
        'ohmy.gif', 'ouch.gif', 'poke.gif', 'puke.gif', 'rant.gif', 'rant2.gif',
        'rofl.gif', 'rolleyes.gif', 'shoot.gif', 'shoot2.gif', 'shutup.gif', 'sick.gif',
        'slaphead.gif', 'sleep.gif', 'sleeping.gif', 'smartass.gif', 'snap.gif',
        'stamp.gif', 'stereo.gif', 'strongbench.gif', 'tears.gif', 'tease.gif',
        'therethere.gif', 'thumbsdown.gif', 'unsure.gif', 'wavecry.gif', 'weakbench.gif',
        'weirdo.gif', 'what.gif', 'whip.gif', 'whistle.gif', 'wiggle.gif', 'wink.gif',
        'worthy.gif', 'wub.gif', 'yawn.gif', 'yikes.gif'); //въведи съответното име на всяка една картинка
    $i = 0;
    foreach ($smiles as $sm) {
        $title = preg_replace('/.(png|gif|jpeg|jpg)/i', '', $smileslink[$i]);
        $text = str_replace(" ".$sm." ", "<img src='$dir/$smileslink[$i]' title='$title'/>", $text);
        $i++;
    }

    $text = nl2br($text); //преобразува всички празни редове до <br />

    $s1s = array('/[table]<br />/is', '/[td]<br />/is', '/[/td]<br />/is',
        '/[tr]<br />/is', '/[/tr]<br />/is', '/<li><br />/is', '/</li><br />/is',
        '/<ol><br />/is', '/<ul><br />/is');
    $bez = array('[table]', '[td]', '[/td]', '[tr]', '[/tr]', '<li>', '</li>',
        '<ol>', '<ul>');
    $text = preg_replace($s1s, $bez, $text); //махам <br /> от някои места за да се изместват нещата

    $text = preg_replace("/[table](.+?)[/table]/is",
        '<table border="1" max-width="600">$1</table>', $text);

    $text = preg_replace("/[tr](.+?)[/tr]/is", '<tr>$1</tr>', $text);

    $text = preg_replace("/[td](.+?)[/td]/is", '<td>$1</td>', $text);

    if (preg_match_all('/[youtube](.+?)[/youtube]/is', $text, $answers, PREG_SET_ORDER)) {
        foreach($answers AS $answer) {			
            if (preg_match('/youtube.com/watch?v=(.+?)([&])/is', $answer[1] . '&', $id)) {
                $embed = '<iframe width="420" height="315" src="http://www.youtube.com/embed/' .
                    $id[1] . '" frameborder="0" allowfullscreen></iframe>';
                $text = str_replace($answer[0], $embed, $text);
            } else
                $text = str_replace($answer[0], '', $text);
        }
    }

    if (preg_match_all('/[vbox7](.+?)[/vbox7]/is', $text, $answers, PREG_SET_ORDER)) {
        foreach($answers AS $answer) {
            if (preg_match('/vbox7.com/play:(.+?)([&])/is', $answer[1] . '&', $id)) {
                $embed = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="450" height="403"><param name="movie" value="http://i48.vbox7.com/player/ext.swf?vid=' .
                    $id[1] . '"><param name="quality" value="high"><embed src="http://i48.vbox7.com/player/ext.swf?vid=' .
                    $id[1] . '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="450" height="403"></embed></object>';
                $text = str_replace($answer[0], $embed, $text);
            } else
                $text = str_replace($answer[0], '', $text);
        }
    }

	$text = preg_replace("/[offtopic](.+?)[/offtopic]/is", 
	'<table class="offtable" cellspacing="1" border="0"><tr><td><input type="button" class="showoff" value="offtopic"/></td></tr><tr><td class="offtopic">$1</td></tr></table>', 
	$text);

    return stripslashes($text); //връща променото съдържание
}
?>
demo.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html;  charset=UTF-8" />
    <title>bbcode editor+parser</title>
	<link rel='stylesheet' href='jQcustom.css' type='text/css' media='all'/> 
	<link rel='stylesheet' href='prettify.css' type='text/css' media='all'/> 
	<link rel='stylesheet' href='BBbutons.css' type='text/css' media='all'/> 
	<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> 
	<script src="jQcustom.js"  type="text/javascript"></script>
	<script src="BBbutons.js"  type="text/javascript"></script> 	
	<script src="prettify.js"  type="text/javascript"></script> 	
	<script>
		$(function() {
			prettyPrint();
		}); 
	</script> 
</head>
<body style="background: #ececec;">	  
	  <form method="post">
	  <script>
	  $(function() {
		$('#area').bbcodetoolbar();
	  }); 
	  </script> 
	  <textarea id="area" name="txtarea" cols="130" rows="20"></textarea><br />
	  <input type="submit" name="submit" value="Прегледай"/>
	  </form>	
	  <br />
	  <?php  
	  if(isset($_POST['submit'])) {
		include "bbcode.php";
		echo bbcode(htmlspecialchars($_POST['txtarea']));
	  }
	  ?>	    	 

	  </form>	
	  -----------------------------------------	  
	  <form method="post">
	  <script>
	  $(function() {
		$('#area2').bbcodetoolbar("b,i,s,img");//отделяте с запетаи бутоните които искате! Вижте js файла за текстовете за бутоните! 
	  }); 
	  </script> 
	  <textarea id="area2" name="txtarea2" cols="130" rows="20"></textarea><br />
	  <input type="submit" name="submit2" value="Прегледай"/>
	  </form>	
	  <br />
	  <?php  
	  if(isset($_POST['submit2'])) {
		include "bbcode.php";
		echo bbcode(htmlspecialchars($_POST['txtarea2']));
	  }
	  ?>	    	 

	  </form>	
	  </body>
	  </html>
Демо
Резервно демо(не е 24/7!)

Всички файлове(включително pretiffy и jQcustom v2 и всички картинки и емотиконки
Резервен архив(не е 24/7!)
Резервен архив 2

Урока в блога ми
Урока в Web-Tourist.net

Надявам се скрипта да ви хареса :) Давам ви свободата да променяте дизайна и функциите както си искате, само да знаете какво правите! :D

При проблеми или въпроси ми пишете коментар или в форума на Web-Tourist.net :)!

Урока е авторски и забранявам копирането му в други сайтове без разрешението ми или това на администраторите!!!
Споделете: