The sub_replace function is used to replace substrings within a string. You can specify the substring to be replaced and the target string to replace it with. It returns a new string where the substring starting from start with length len in str is replaced by new_str. If start or len is a negative integer, it returns NULL. The default value for len is the length of new_str.
sub_replace(<str>, <new_str>, [ ,<start> [ , <len> ] ])
| Parameter | Description |
|---|---|
<str> | The target string in which the replacement will occur |
<new_str> | The string that will replace the specified substring |
<start> | start is the position where the replacement operation begins, indicating from which position in the string the replacement will start |
<len> | len is an optional parameter that specifies the length of the substring to be replaced |
Returns the string after replacement.
SELECT sub_replace('doris', '***', 1, 2);
+-----------------------------------+ | sub_replace('doris', '***', 1, 2) | +-----------------------------------+ | d***is | +-----------------------------------+
SELECT sub_replace('hello', 'Hi', 0);
+--------------------------------+ | sub_replace('hello', 'Hi', 0) | +--------------------------------+ | Hillo | +--------------------------------+
SELECT sub_replace('hello', 'Hi', -1, 2);
+------------------------------------+ | sub_replace('hello', 'Hi', -1, 2) | +------------------------------------+ | NULL | +------------------------------------+
SELECT sub_replace(NULL, 'new', 0, 3);
+-------------------------------------+ | sub_replace(NULL, 'new', 0, 3) | +-------------------------------------+ | NULL | +-------------------------------------+
SELECT sub_replace('doris', 'ṛìḍḍ', 1, 2);
+-------------------------------------------+ | sub_replace('doris', 'ṛìḍḍ', 1, 2) | +-------------------------------------------+ | dṛìḍḍis | +-------------------------------------------+
SELECT sub_replace('hello', 'Hi', 9, 2);
+----------------------------------+ | sub_replace('hello', 'Hi', 9, 2) | +----------------------------------+ | NULL | +----------------------------------+
SELECT sub_replace('hello', 'Hi', 1, 9);
+----------------------------------+ | sub_replace('hello', 'Hi', 1, 9) | +----------------------------------+ | hHi | +----------------------------------+
SUB_REPLACE, REPLACE