PHP实现HTML转UBB

/**
* 解析HTML为UBB函数
*
* @param string $str 要解析的字符串
* @return string
*/
function parse($str)
{
$str = str_replace("\n",'',$str);
$str = preg_replace("/\<A[^>]+HREF=\"([^\"]+)\"[^>]*\>(.*?)<\/a\>/i","[url=$1]$2[/url]",$str);
$str = preg_replace("/\<font(.*?)color=\"#([^ >]+)\"(.*?)\>(.*?)<\/font>/i","<font$1$3>[color=$2]$4[/color]</font>",$str);
$str = preg_replace("/\<font(.*?)face=\"([^ >]+)\"(.*?)\>(.*?)<\/font>/i","<font$1$3>[face=$2]$4[/face]</font>",$str);
$str = preg_replace("/\<font(.*?)size=\"([^ >]+)\"(.*?)\>(.*?)<\/font>/i","[size=$2]$4[/size]",$str);
$str = preg_replace("/\<img[^>]+src=\"([^\"]+)\"[^>]*\>/i","[img]$1[/img]",$str);
$str = preg_replace("/\<DIV[^>]+ALIGN=\"([^\"]+)\"[^>]*\>(.*?)<\/DIV\>/i","[align=$1]$2[/align]",$str);
$str = preg_replace("/\<([\/]?)u\>/i","[$1u]",$str);
$str = preg_replace("/\<([\/]?)em\>/i","[$1I]",$str);
$str = preg_replace("/\<([\/]?)strong\>/i","[$1b]",$str);
$str = preg_replace("/\<([\/]?)b(.*?)\>/i","[$1b]",$str);
$str = preg_replace("/\<([\/]?)i\>/i","[$1i]",$str);
$str = preg_replace("/<[^>]*?>/i","",$str);
return $str;
}
//其中对<B>内包含其它的属性进行了处理,对<U>、<EM>、<I>、<STRONG>没有进行处理。
//注:另写了一个用XML解析的方法来实现,但其容错性较差,对要进行转换的HTML文档要求太高,实用性较低。故重新用正则替换来实现。
//修改自一段ASP的代码:原ASP代码如下
<%
function html2ubb(l1)
if len(trim(l1))>0 then
else
exit function
end if
dim l4,I1,I2,I3
dim i,I4:I4=array(16,19,21,24,32,45)
I1=l1
set I2=new regexp
I2.global=true
I2.ignorecase=true'忽略大小写
I2.pattern="/r":I1=I2.replace(I1,"")
I2.pattern="on(load|click|dbclick|mouseover|mousedown|mouseup)=""[^""]+""":I1=I2.replace(I1,"")
I2.pattern="<script[^>]*?>([\w\W]*?)<\/script>":I1=I2.replace(I1,"")
I2.pattern="<a[^>]+href=""([^""]+)""[^>]*>(.*?)<\/a>":I1=I2.replace(I1,"[url=$1]$2[/url]")
I2.pattern="<font[^>]+color=([^ >]+)[^>]*>(.*?)<\/font>":I1=I2.replace(I1,"[color=$1]$2[/color]")
I2.pattern="<img[^>]+src=""([^""]+)""[^>]*>":I1=I2.replace(I1,"[img]$1[/img]")
I2.pattern="<([\/]?)b>":I1=I2.replace(I1,"[$1b]")
I2.pattern="<([\/]?)strong>":I1=I2.replace(I1,"[$1b]")
I2.pattern="<([\/]?)u>":I1=I2.replace(I1,"[$1u]")
I2.pattern="<([\/]?)i>":I1=I2.replace(I1,"[$1i]")
I2.pattern=" ":I1=I2.replace(I1," ")
I2.pattern="&":I1=I2.replace(I1,"&")
I2.pattern="""":I1=I2.replace(I1,"""")
I2.pattern="<":I1=I2.replace(I1,"<")
I2.pattern=">":I1=I2.replace(I1,">")
I2.pattern="<br />":I1=I2.replace(I1,vbcrlf)
I2.pattern="<[^>]*?>":I1=I2.replace(I1,"")
I2.pattern="\n+":I1=I2.replace(I1,vbcrlf)
set I2=nothing
html2ubb=I1

end function

response.write html2ubb("蓝雨设计<img src=""logo.gif"">")
%>