MySQL 中替换函数 REPLACE(s,s1,s2) 使用字符串 s2 替换字符串 s 中所有的字符串 s1。
【实例】使用 REPLACE 函数进行字符串替换操作,输入的 SQL 语句和执行过程如下所示。
mysql> SELECT REPLACE('aaa.mysql.com','a','w');
+----------------------------------+
| REPLACE('aaa.mysql.com','a','w') |
+----------------------------------+
| www.mysql.com |
+----------------------------------+
1 row in set (0.00 sec)
由运行结果可以看出,使用 REPLACE('aaa.mysql.com','a','w') 将“aaa.mysql.com”字符串的“a”字符替换为“w”字符,结果为“www.mysql.com”。
mysql替换部分字符串
1、使用REPLACE()函数
REPLACE()函数用新的子字符串替换字符串中所有出现的子字符串。
注意:此函数执行区分大小写的替换。
语法
1 | REPLACE(string, from_string, new_string) |
参数 | 描述 |
---|---|
string | 必须项。原始字符串 |
from_string | 必须项。要替换的子字符串 |
new_string | 必须项。新的替换子字符串 |
【实例】使用 REPLACE 函数进行字符串替换操作
1 2 3 4 5 6 7 | mysql> SELECT REPLACE( 'aaa.mysql.com' , 'a' , 'w' ); +----------------------------------+ | REPLACE( 'aaa.mysql.com' , 'a' , 'w' ) | +----------------------------------+ | www.mysql.com | +----------------------------------+ 1 row in set (0.00 sec) |
由运行结果可以看出,使用 REPLACE('aaa.mysql.com','a','w')
将“aaa.mysql.com
”字符串的“a”字符替换为“w”字符,结果为“www.mysql.com
”。
UPDATE name SET path = REPLACE (name,'http://www.baidu.com/','http://111.baidu.com')
2、使用INSERT()函数
INSERT()函数在指定位置的字符串中插入一个字符串,并插入一定数量的字符。
语法
1 | INSERT(string, position, number, string2) |
参数 | 描述 |
---|---|
string | 必须项。要修改的字符串 |
position | 必须项。插入string2的位置 |
number | 必须项。要替换的字符数 |
string2 | 必须项。要插入字符串的字符串 |
若 position 超过字符串长度,则返回值为原始字符串。假如 number 的长度大于其他字符串的长度,则从位置 position 开始替换。若任何一个参数为 NULL,则返回值为 NULL。
【实例】使用 INSERT 函数进行字符串替换操作
1 2 3 4 5 6 7 8 9 | mysql> SELECT INSERT( 'Football' ,2,4, 'Play' ) AS col1, -> INSERT( 'Football' ,-1,4, 'Play' ) AS col2, -> INSERT( 'Football' ,3,20, 'Play' ) AS col3; +----------+----------+--------+ | col1 | col2 | col3 | +----------+----------+--------+ | FPlayall | Football | FoPlay | +----------+----------+--------+ 1 row in set (0.04 sec) |
由执行结果可知:
第一个函数
INSERT('Football',2,4,'Play')
将“Football”从第 2 个字符开始长度为 4 的字符串替换为 Play,结果为“FPlayall”;第二个函数
INSERT('Football',-1,4,'Play')
中的起始位置 -1 超出了字符串长度,直接返回原字符串;第三个函数
INSERT('Football',3,20,'Play')
替换长度超出了原字符串长度,则从第 3 个字符开始,截取后面所有的字符,并替换为指定字符 Play,结果为“FoPlay”。
发表评论 取消回复