mysql本身没有去除html代码的内置函数,但是在一些情况下,不得不在数据库层次提取一些去除了html代码的纯文本,经过谷歌后,找到了以下两个函数,经测试,均可用.
SQL代码:
- SET GLOBAL log_bin_trust_function_creators=1;
- DROP FUNCTION IF EXISTS fnStripTags;
- DELIMITER |
- CREATE FUNCTION fnStripTags( Dirty varchar(4000) )
- RETURNS varchar(4000) --Vevb.com
- DETERMINISTIC
- BEGIN
- DECLARE iStart, iEnd, iLength int;
- WHILE Locate( '<', Dirty ) > 0 And Locate( '>', Dirty, Locate( '<', Dirty )) > 0 DO
- BEGIN
- SET iStart = Locate( '<', Dirty ), iEnd = Locate( '>', Dirty, Locate('<', Dirty ));
- SET iLength = ( iEnd - iStart) + 1;
- IF iLength > 0 THEN
- BEGIN
- SET Dirty = Insert( Dirty, iStart, iLength, '');
- END;
- END IF;
- END;
- END WHILE;
- RETURN Dirty;
- END;
- |
- DELIMITER ;
- SELECT fnStripTags('this <html>is <b>a test</b>, nothing more</html>');
函数2:
- CREATE FUNCTION `strip_tags`($str text) RETURNS text
- BEGIN
- DECLARE $start, $end INT DEFAULT 1;
- LOOP
- SET $start = LOCATE("<", $str, $start);
- IF (!$start) THEN RETURN $str; END IF;
- SET $end = LOCATE(">", $str, $start);
- IF (!$end) THEN SET $end = $start; END IF;
- SET $str = INSERT($str, $start, $end - $start + 1, "");
- END LOOP;
- END;
- select strip_tags('<span>hel<b>lo <a href="world">wo<>rld</a> <<x>again<.');
补充:如果你是php程序员就不需要上面的方法了,直接有现在的代码.
- <?php
- $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
- echo strip_tags($text);
- echo " ";
- // 允许 <p> 和 <a>
- echo strip_tags($text, '<p><a>');
- ?>
- //以上例程会输出:
- Test paragraph. Other text
- <p>Test paragraph.</p> <a href="#fragment">Other text</a>
新闻热点
疑难解答