What is the MySQL query equivalent of PHP strip_tags?

后端 未结 9 781
情书的邮戳
情书的邮戳 2020-11-27 18:49

I have a large database which contains records that have tags in them and I would like to remove them. Of course there is the method where I create a

9条回答
  •  北海茫月
    2020-11-27 18:59

    I just extended the answer @boann to allow targetting of any specific tag so that we can replace out the tags one by one with each function call. You just need pass the tag parameter, e.g. 'a' to replace out all opening/closing anchor tags. This answers the question asked by OP, unlike the accepted answer, which strips out ALL tags.

    # MySQL function to programmatically replace out specified html tags from text/html fields
    
    # run this to drop/update the stored function
    DROP FUNCTION IF EXISTS `strip_tags`;
    
    DELIMITER |
    
    # function to nuke all opening and closing tags of type specified in argument 2
    CREATE FUNCTION `strip_tags`($str text, $tag text) RETURNS text
    BEGIN
        DECLARE $start, $end INT DEFAULT 1;
        SET $str = COALESCE($str, '');
        LOOP
            SET $start = LOCATE(CONCAT('<', $tag), $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, '');
            SET $str = REPLACE($str, CONCAT(''), '');
        END LOOP;
    END;
    
    | DELIMITER ;
    
    # test select to nuke all opening  tags
    SELECT 
        STRIP_TAGS(description, 'a') AS stripped
    FROM
        tmpcat;
    
    # run update query to replace out all  tags
    UPDATE tmpcat
    SET 
        description = STRIP_TAGS(description, 'a');
    

提交回复
热议问题