在日常开发中,我们会遇到需要在数据库中对通过web网站中文本编辑器提交上来的内容进行一些特殊处理等,此处是针对mysql数据库中去除字符串中的html标签SQL语句。
直接贴上代码:
SET GLOBAL log_bin_trust_function_creators = 1;
DROP FUNCTION
IF
EXISTS fnStripTags;
DELIMITER |
CREATE FUNCTION fnStripTags ( Dirty LONGTEXT ) /*这里的longtext根据需要处理的字符串或字段类型自行定义*/
RETURNS LONGTEXT /*这里的longtext根据需要处理的字符串或字段类型自行定义*/
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;
使用函数SQL:
select id,content,fnStripTags(content) asnewcontent from collectedworkstable order by id desc limit 100
示例图:
以下是未验证过的网上版本:
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>达健身房<b>lo <a href="34234234">傻傻的和<>rld</a> <<x>again<.');
上边是整理的Mysql中清除html代码的SQL语句。
给大家推荐一个比较好用的在线工具:首页|爱工具(AI工具)方便实用的在线服务工具