我目前正在为我的应用程序开发一个搜索和替换功能,我希望它能够在字符串的开头/结尾替换指定的字符串。例如:
string = "DadaLalaDada"
得到
string = "DuduLalaDada"
当在字符串的开头搜索并替换为
search = "Dada"
replace = "Dudu"
被执行。
我怎样才能在 MySQL 中做到这一点?我使用REPLACE来命中字符串中的每一个匹配项,但如何仅在开头/结尾执行此操作?
如果您愿意在查询中多次出现相关值,这似乎可行:
select tab.val,
concat(replace(substring(tab.val, 1, char_length('Dada')), 'Dada', 'Dudu'),
substring(tab.val, char_length('Dada') + 1)) as replace_beginning,
concat(substring(tab.val, 1, char_length(tab.val) - char_length('Dada')),
replace(substring(tab.val, -char_length('Dada')), 'Dada', 'Dudu')) as replace_end
from ( select "DadaLalaDada" as val union select "BlahDadaBlah" ) as tab
结果:
+--------------+-------------------+--------------+
| val | replace_beginning | replace_end |
+--------------+-------------------+--------------+
| DadaLalaDada | DuduLalaDada | DadaLalaDudu |
| BlahDadaBlah | BlahDadaBlah | BlahDadaBlah |
+--------------+-------------------+--------------+