1

I want to replace exact word in mysql.

For example, I want to replace 'u' with 'you' in a sentence. sentence: are u sure. output : are you sure.

I tried use replace but it is also changing 'u' in 'sure'. but i can't get the exact word to replace

Also i want change the cases where u like "u, can" , "can u?" , "u" , "u r a beauty" where every line is in each row of the database and column type is TEXT.

I need update query.

Black Rose
  • 27
  • 5

2 Answers2

1

You have wrong parameter the replace format in this case is not set columnname = replace(columnname,'you','u') but replace(columnname,'u','you') and you should also check for word boundaries .. ' u ' and you could use also like

update table 
set columnname = replace(columnname,' u ',' you ') 
where columnname  like '% u %' ; 

but if you have several cases the you should manage each case properly eg for ' u ' and ' u,'

update table 
set columnname = case when columnname  like '% u %'
                        then  replace(columnname,' u ',' you ') 
                      when columnname  like '% u,%'
                        then  replace(columnname,' u,',' you,') 
                 end
where columnname  like '% u %'
OR columnname  like '% u,%' ; 

If you have mysql 8 you could use regexp_replace

 update table 
 set columnname = REGEXP_REPLACE(columnname,'[[:<:]]u[[:>:]]','you') 
 where columnname regexp '[[:<:]]u[[:>:]]';

..

select REGEXP_REPLACE('test u tesp','[[:<:]]u[[:>:]]','you') 
from dual
where 'test u tesp' regexp '[[:<:]]u[[:>:]]';
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/198068/discussion-on-answer-by-scaisedge-i-want-replace-exact-word-in-mysql). – Bhargav Rao Aug 17 '19 at 04:32
0

If you want an exact word you should include the spaces around the word. so rather than replace(columnname,'you','u') you use replace(columnname,' you ',' u ') That should cover the situation you described

I tried use replace but it is also changing 'u' in 'sure'. but i can't get the exact word to replace

Spasnof
  • 141
  • 1
  • 5