在一些小型論壇或者是小型的評論系統中,經常會遇到“支持UBB”之類的術語,其實UBB代碼是HTML的一個變種,通過程序自定義我們的標簽,比如“[a]PHP中UBB的使用[/a]”這樣的標簽,其實質就是利用技術查找[a][/a]標簽,將其替換成的標準html,說白了,就是將 標準的 html 標記通過技術手段使其簡化,其輸出出來的結果還是標準的 html。
明白了 ubb 的原理,那么再制作一個簡單的 ubb 編輯器就不難了,和 fck 之類的編輯器比較起來,ubb 代碼最大的優點就是代碼簡單,功能很少,簡單的ubb只需要一個文件,而且 ubb 標簽可以自己來定義,更改起來很方便,在 php 中就是利用替換函數就可以將 html 進行標簽化,輸出時進行標簽的轉化,下面是一個 php 中 UBB 使用的源碼,僅一個文件,就實現了 ubb 編輯器,網絡上有許多變種的 UBB 代碼,核心的原理基本上都是一樣的。
小說明:[a]http://www.04ie.com[/a] 實際標準的html為 <a href=http://www.04ie.com >http://www.04ie.com</a>,UBB 編輯器將 <a href=http://www.04ie.com >http://www.04ie.com</a> 進行了標簽化,也就是 [a]http://www.04ie.com[/a],通過 ubb 標簽,代碼是不是簡潔了許多。
PHP簡單UBB界面預覽:
代碼如下:
<?php
/*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
function get_ubb($str)
{
//[a][/a]超鏈接
$str=preg_replace("//[a/](.*)/[//a/]/i","<a href=//1 >//1</a>",$s
tr);
//QQ號碼UBB
$str = preg_replace("//[qq/]([0-9]*)/[//qq/]/i", "<a target=/"_blan
k/" href=/"tencent://message/?uin=/${1}&site=www.60ie.net&menu=ye
s/"><img src=/"http://wpa.qq.com/pa?p=1:/${1}:8/" alt=/"QQ/${1}/" h
eight=/"16/" border=/"0/" align=/"top/" /></a>", $str);
//[]超鏈接
$str=preg_replace("//[img/](.*?)/[//img/]/i","<img src=//1 />",$s
tr);
return $str;
}
if($_POST['sub'])
{
echo $ss=get_ubb($_POST['text']);
}
?>
<script>
function inserttag(topen,tclose){
var themess = document.getElementById('test');//編輯對象
themess.focus();
if (document.selection) {//如果是否ie瀏覽器
var theSelection = document.selection.createRange().text;//獲
//取選區文字
//alert(theSelection);
if(theSelection){
document.selection.createRange().text = theSelection = tope
n+theSelection+tclose;//替換
}else{
document.selection.createRange().text = topen+tclose;
}
theSelection='';
}else{//其他瀏覽器
var scrollPos = themess.scrollTop;
var selLength = themess.textLength;
var selStart = themess.selectionStart;//選區起始點索引,未選擇為0
var selEnd = themess.selectionEnd;//選區終點點索引
if (selEnd <= 2)
selEnd = selLength;
var s1 = (themess.value).substring(0,selStart);//截取起始點前部分
//字符
var s2 = (themess.value).substring(selStart, selEnd)//截取選擇部
//分字符
var s3 = (themess.value).substring(selEnd, selLength);//截取終
//點后部分字符
themess.value = s1 + topen + s2 + tclose + s3;//替換
themess.focus();
themess.selectionStart = newStart;
themess.selectionEnd = newStart;
themess.scrollTop = scrollPos;
return;
}
}
</script><style type="text/css">
<!--
a {
font-size: 12px;
}
-->
</style>
<hr/>
<form action="" method="post">
<a href="javascript:void(0);" onclick='inserttag("[a]","[/a
]");'>添加A標簽</a>
<a href="javascript:void(0);" onclick='inserttag("[qq]","[/q
q]");'>添加QQ標簽</a>
<a href="javascript:void(0);" onclick='inserttag("[img]","[/i
mg]");'>添加IMG標簽</a><br/>
<textarea id="test" name="text" rows="10" cols="50" wrap="of
f"></textarea><br/>
<input type="submit" name="sub" value="提交"/>
</form>
新聞熱點
疑難解答