有如下一个html字符串保存在mysql数据库中:
<div> <p>文本</p> <figure>广告<img src="a.jpg" /></figure> <p>文本</p> </div>
现在要从数据库数据中删除中间的广告标签,如何用mysql语句实现?
首先,如果我们用一句mysql语句:
select Insert( post_content, Locate( '<figure>', post_content ), Locate( '</figure>', post_content, Locate( '<figure>', post_content )) - Locate( "<figure>", post_content ) + LENGTH('</figure>'), '' ) as new_content from wp_posts where ID=146;
substr
,str)或LOCATE(substr
,str,pos):查找字符串第一次出现的位置。这样我们就能查出删除了第一个 <figure> 标签的内容,但是如果有多个标签,则剩下的标签没有替换。
那么,我们就用存储过程来解决:
SET GLOBAL log_bin_trust_function_creators=1; DROP FUNCTION IF EXISTS fnStripTags; DELIMITER | CREATE FUNCTION fnStripTags( Dirty longtext, BeginStr varchar(30), EndStr varchar(30) ) RETURNS longtext DETERMINISTIC BEGIN DECLARE iStart, iEnd, iLength int; WHILE Locate( BeginStr, Dirty ) > 0 And Locate( EndStr, Dirty, Locate( BeginStr, Dirty )) > 0 DO BEGIN SET iStart = Locate( BeginStr, Dirty ), iEnd = Locate( EndStr, Dirty, Locate( BeginStr, Dirty )); SET iLength = ( iEnd - iStart ) + LENGTH( EndStr ); IF iLength > 0 THEN BEGIN SET Dirty = Insert( Dirty, iStart, iLength, ''); END; END IF; END; END WHILE; RETURN Dirty; END; | DELIMITER ;
再调用就可以了:
select LENGTH(post_content), post_content from wp_posts where ID=146;
如果要更改内容,直接用update语句就能完成:
update wp_posts set post_content = fnStripTags(post_content, '<figure>', '</figure>') where ID=146;
同样,如果是其他DOM格式,也是可以的,例如:
update wp_posts set post_content = fnStripTags(post_content, '<div>', '</div>') where ID=146;
功效是一样的。