实际上,在php中,ubb代码是html的一种变种,它的全称是Ultimate Bullrtin Board.例子如下:
[url]www.51cto.com[/url]
[b]php学习[/b]
[swf]../image/demo.swf[/swf]
它的优点是,实现一些我们基本常用的一些功能,使用起来也更加便利,而且相对html安全性更高一些,同时呢,也有效的减少了数据库存储代码,它的缺点是排版功能比较弱,同时也不允许标签之间的交叉嵌套使用。
它的运行过程有两种模式,ubb->db->解析->输出;ubb->解析->db->输出,其中前者更为规范一些。
下面就是实例。
新建一个test工程 ,新建一个ubb.php:
function get_ubb($str) {
$str = preg_replace("/(\[)em(.*?)(\])/i", "<img src=\"2.jpeg\" />", $str);
//链接UBB
$str = preg_replace("/(\[url\])(.*)(\[\/url\])/i", "<a href=\\2 target=\"new\">\\2</a>", $str);
//QQ号码UBB
$str = preg_replace("/\[qq\]([0-9]*)\[\/qq\]/i", "<a target=\"_blank\" href=\"tencent://message/?uin=\${1}&site=www.php100.com&menu=yes\"><img src=\"http://wpa.qq.com/pa?p=1:\${1}:8\" alt=\"QQ\${1}\" height=\"16\" border=\"0\" align=\"top\" /></a>", $str);
$str = preg_replace("/(\[b\])(.*)(\[\/b\])/", "<b>\\2</b>", $str);
return $str;
}
if($_POST['sub']){
echo get_ubb($_POST[message]);
}
?>
<script>
function inserttag(topen,tclose){
var themess = document.getElementById('con');//编辑对象
themess.focus();
if (document.selection) {//如果是否ie浏览器
var theSelection = document.selection.createRange().text;//获取选区文字
//alert(theSelection);
if(theSelection){
document.selection.createRange().text = theSelection = topen+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>
<form action="" method="post" align="center">
<hr/>
<font size=2>
<img class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="2.jpeg" />
<a href="javascript:void(0);" onclick='inserttag("[b]","[/b]");'>加粗</a>
<a href="javascript:void(0);" onclick='inserttag("[qq]","[/qq]");'>QQ号</a>
<a href="javascript:void(0);" onclick='inserttag("[url]","[/url]");'>超链接</a>
<br>
<textarea name="message" id="con" cols="70%" rows="10"></textarea>
<br>
<input type="submit" name="sub" value="提交"/>
</form>
共同学习,写下你的评论
评论加载中...
作者其他优质文章