Remove special characters from a database field

前端 未结 10 1678
梦如初夏
梦如初夏 2020-12-06 01:00

I have a database with several thousand records, and I need to strip down one of the fields to ensure that it only contains certain characters (Alphanumeric, spaces, and sin

10条回答
  •  Happy的楠姐
    2020-12-06 01:41

    I have created simple function for this

    DROP FUNCTION IF EXISTS `regex_replace`$$
    
    CREATE FUNCTION `regex_replace`(pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000)) RETURNS VARCHAR(1000) CHARSET utf8mb4
        DETERMINISTIC
    BEGIN    
        DECLARE temp VARCHAR(1000); 
        DECLARE ch VARCHAR(1); 
        DECLARE i INT;
        SET i = 1;
        SET temp = '';
        IF original REGEXP pattern THEN 
            loop_label: LOOP 
                IF i>CHAR_LENGTH(original) THEN
                    LEAVE loop_label;  
                END IF;
    
                SET ch = SUBSTRING(original,i,1);
    
                IF NOT ch REGEXP pattern THEN
                    SET temp = CONCAT(temp,ch);
                ELSE
                    SET temp = CONCAT(temp,replacement);
                END IF;
    
                SET i=i+1;
            END LOOP;
        ELSE
            SET temp = original;
        END IF;
    
        RETURN temp;
    END
    

    Usage example:

    SELECT  AS NormalText, regex_replace('[^A-Za-z0-9 ]', '', )AS RegexText FROM 
    
    

提交回复
热议问题