mysql本身没有去除html代码的内置函数,但是在一些情况下,不得不在数据库层次提取一些去除了html代码的纯文本,经过谷歌后,找到了以下两个函数,经测试,均可用.
SQL代码:
- SETGLOBALlog_bin_trust_function_creators=1;
- DROPFUNCTIONIFEXISTSfnStripTags;
- DELIMITER|
- CREATEFUNCTIONfnStripTags(Dirtyvarchar(4000))
- RETURNSvarchar(4000)--phpfensi.com
- DETERMINISTIC
- BEGIN
- DECLAREiStart,iEnd,iLengthint;
- WHILELocate('<',Dirty)>0AndLocate('>',Dirty,Locate('<',Dirty))>0DO
- BEGIN
- SETiStart=Locate('<',Dirty),iEnd=Locate('>',Dirty,Locate('<',Dirty));
- SETiLength=(iEnd-iStart)+1;
- IFiLength>0THEN
- BEGIN
- SETDirty=Insert(Dirty,iStart,iLength,'');
- END;
- ENDIF;
- END;
- ENDWHILE;
- RETURNDirty;
- END;
- |
- DELIMITER;
- SELECTfnStripTags('this<html>is<b>atest</b>,nothingmore</html>');
函数2:
- CREATEFUNCTION`strip_tags`($strtext)RETURNStext
- BEGIN
- DECLARE$start,$endINTDEFAULT1;
- LOOP
- SET$start=LOCATE("<",$str,$start);
- IF(!$start)THENRETURN$str;ENDIF;
- SET$end=LOCATE(">",$str,$start);
- IF(!$end)THENSET$end=$start;ENDIF;
- SET$str=INSERT($str,$start,$end-$start+1,"");
- ENDLOOP;
- END;
- selectstrip_tags('<span>hel<b>lo<ahref="world">wo<>rld</a><<x>again<.');
补充:如果你是php程序员就不需要上面的方法了,直接有现在的代码.
- <?php
- $text='<p>Testparagraph.</p><!--Comment--><ahref="#fragment">Othertext</a>';
- echostrip_tags($text);
- echo"";
- //允许<p>和<a>
- echostrip_tags($text,'<p><a>');
- ?>
- //以上例程会输出:
- Testparagraph.Othertext
- <p>Testparagraph.</p><ahref="#fragment">Othertext</a>