tags:

views:

1226

answers:

2

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.

+4  A: 

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 ;)

Andomar
what!? no it won't :)
Zak
@Zak: eh... right, you actually read the query? I'll edit it ;)
Andomar
Sorry, meant to put in the question I've been using nested REPLACEs. I was hoping for something similar to PHP's `str_replace` function, but I guess it doesn't exist.
DisgruntledGoat
Andomar: MySQL doesn't support the `WITH` clause; no one should be providing a CTE equivalent query...
OMG Ponies
upvoted for correction
Zak
+1  A: 

I would suggest running a program to loop over your records, process the fields, then update them. Maybe a simple perl or php script.

Zak