george varghees
george varghees

Reputation: 11

MySQL function to replace text keeping the case intact

Requirement is replace case sensitive text in column value based on a US English dictionary

Below are the samples

Colour => color
Color => Color (note that C is capitalized here)

FIBRE => FIBER

Colour/Monochrome => Color/Monochrome

Upvotes: 1

Views: 243

Answers (1)

caitriona
caitriona

Reputation: 9131

Try this:

DELIMITER $$
DROP FUNCTION IF EXISTS `replace_ci`$$
CREATE FUNCTION `replace_ci` (str TEXT, needle CHAR(255), str_rep CHAR(255))
    RETURNS TEXT
    DETERMINISTIC
    BEGIN
        DECLARE return_str TEXT DEFAULT '';
        DECLARE lower_str TEXT;
        DECLARE lower_needle TEXT;
        DECLARE pos INT DEFAULT 1;
        DECLARE old_pos INT DEFAULT 1;
        SELECT lower(str) INTO lower_str;
        SELECT lower(needle) INTO lower_needle;
        SELECT locate(lower_needle, lower_str, pos) INTO pos;
        WHILE pos > 0 DO
            SELECT concat(return_str, substr(str, old_pos, pos-old_pos), str_rep) INTO return_str;
            SELECT pos + char_length(needle) INTO pos;
            SELECT pos INTO old_pos;
            SELECT locate(lower_needle, lower_str, pos) INTO pos;
        END WHILE;
        SELECT concat(return_str, substr(str, old_pos, char_length(str))) INTO return_str;

        /** mirror the case **/
        IF (BINARY LEFT(str,1) = LOWER(LEFT(str,1))) THEN
            SET return_str = LOWER(return_str);
        ELSE
            IF (BINARY LEFT(str,2) = UPPER(LEFT(str,2))) THEN
                SET return_str = UPPER(return_str);
            ELSE          
                SET return_str = CONCAT( UPPER(LEFT(return_str,1)), LOWER(RIGHT(return_str, LENGTH(return_str) - 1)) );
            END IF;
        END IF;

        RETURN return_str;
END$$
DELIMITER ;

I've modified the case-insensitive replace function (that was mentioned in the other answer) to 'mirror' the case of the original string

(See the section of code after /** mirror the case **/).

However, it only checks for 3 scenarios - that the input string was either

  • lowercase
  • uppercase
  • first letter capital

but it should work for those three scenarios - ie

FIBRE => FIBER

Fibre => Fiber

fibre => fiber

Upvotes: 0

Related Questions