Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can MySQL replace multiple characters?

I'm trying to replace a bunch of characters in a MySQL field. I know the REPLACE function but that only replaces one string at a time. I can't see any appropriate functions in the manual.

Can I replace or delete multiple strings at once? For example I need to replace spaces with dashes and remove other punctuation.

like image 473
DisgruntledGoat Avatar asked Nov 04 '09 00:11

DisgruntledGoat


People also ask

How do I replace multiple characters in SQL?

Using the REPLACE() function will allow you to change a single character or multiple values within a string, whether working to SELECT or UPDATE data.

How do I replace multiple characters in a string?

Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.

How do you replace all letters in a string in SQL?

SQL Server REPLACE() FunctionThe REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive. Tip: Also look at the STUFF() function.


2 Answers

You can chain REPLACE functions:

select replace(replace('hello world','world','earth'),'hello','hi') 

This will print hi earth.

You can even use subqueries to replace multiple strings!

select replace(london_english,'hello','hi') as warwickshire_english from (     select replace('hello world','world','earth') as london_english ) sub 

Or use a JOIN to replace them:

select group_concat(newword separator ' ') from (     select 'hello' as oldword     union all     select 'world' ) orig inner join (     select 'hello' as oldword, 'hi' as newword     union all     select 'world', 'earth' ) trans on orig.oldword = trans.oldword 

I'll leave translation using common table expressions as an exercise for the reader ;)

like image 108
Andomar Avatar answered Sep 19 '22 13:09

Andomar


Cascading is the only simple and straight-forward solution to mysql for multiple character replacement.

UPDATE table1  SET column1 = replace(replace(REPLACE(column1, '\r\n', ''), '<br />',''), '<\r>','') 
like image 26
Anurag Avatar answered Sep 17 '22 13:09

Anurag