MySQL查找和替换HTML DOM标签

984 记录 发表评论

有如下一个html字符串保存在mysql数据库中:

<div class="content">
    <p>文本</p>
    <figure>广告<img src="a.jpg" /></figure>
    <p>文本</p>
</div>

现在要从数据库数据中删除中间的广告标签,如何用mysql语句实现?

我们要用到两个主要函数:LOCATEINSERT

第1步 一句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 tmpe04d7e_posts where ID=146;  
  • LOCATE(substr,str)LOCATE(substr,str,pos):查找字符串第一次出现的位置。
  • INSERT(str, pos, len, newstr):将字符串中指定位置和长度的子字符串替换为另外一个字符串。

这样我们就能查出删除了第一个 <figure> 标签的内容,但是如果有多个标签,则剩下的标签没有替换。

第2步 存储过程替换

那么,我们就用存储过程来解决:

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 tmpe04d7e_posts where ID=146;	

第3步 更新

如果要更改内容,直接用update语句就能完成:

update tmpe04d7e_posts set post_content = fnStripTags(post_content, '<figure>', '</figure>') where ID=146;

同样,如果是其他DOM格式,也是可以的,例如:

update tmpe04d7e_posts set post_content = fnStripTags(post_content, '<div class="ad">', '</div>') where ID=146;

功效是一样的。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

昵称 *