我正在开发一个搜索&替换我的应用程序的函数,我希望它能够替换字符串的开头/结尾的指定字符串。 例如:
string = "DadaLalaDada"
得
string = "DuduLalaDada"
搜索&使用
替换字符串的开头search = "Dada"
replace = "Dudu"
已完成。
我如何在MySQL中执行此操作?我使用 REPLACE 命中字符串中的每一个匹配项,但是如何仅在开头/结尾执行此操作?
答案 0 :(得分:2)
如果您愿意在查询中多次显示相关值,这似乎有效:
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 |
+--------------+-------------------+--------------+