SQL: search/replace but only the first time a value appears in record

后端 未结 9 817
执念已碎
执念已碎 2020-12-11 02:11

I have html content in the post_content column.

I want to search and replace A with B but only the first time A appears in the record as it may appear more than onc

9条回答
  •  遥遥无期
    2020-12-11 03:01

    Years have passed since this question was asked, and MySQL 8 has introduced REGEX_REPLACE:

    REGEXP_REPLACE(expr, pat, repl[, pos[, occurrence[, match_type]]])

    Replaces occurrences in the string expr that match the regular expression specified by the pattern pat with the replacement string repl, and returns the resulting string. If expr, pat, or repl is NULL, the return value is NULL.

    REGEXP_REPLACE() takes these optional arguments:

    pos: The position in expr at which to start the search. If omitted, the default is 1.
    occurrence: Which occurrence of a match to replace. If omitted, the default is 0 (which means “replace all occurrences”).
    match_type: A string that specifies how to perform matching. The meaning is as described for REGEXP_LIKE().

    So, assuming you can use regular expressions in your case:

    UPDATE wp_posts SET post_content = REGEXP_REPLACE (post_content, 'A', 'B', 1, 1);
    

    Unfortunately for those of us on MariaDB, its REGEXP_REPLACE flavor is missing the occurrence parameter. Here's a regex-aware version of Andriy M's solution, conveniently stored as a reusable function as suggested by Luciano Seibel:

    DELIMITER //
    DROP FUNCTION IF EXISTS replace_first //
    CREATE FUNCTION `replace_first`(
        `i` TEXT,
        `s` TEXT,
        `r` TEXT
    )
    RETURNS text CHARSET utf8mb4
    BEGIN
        SELECT REGEXP_INSTR(i, s) INTO @pos;
        IF @pos = 0 THEN RETURN i; END IF;
        RETURN INSERT(i, @pos, CHAR_LENGTH(REGEXP_SUBSTR(i, s)), r);
    END;
    //
    DELIMITER ;
    

提交回复
热议问题