Question

How do you perform the following PHP function in MySQL using UPDATE, SET and REPLACE?

preg_replace('/\s+/', ' ', $string);

from Remove multiple whitespaces

EDIT QUESTION

My objectif is to go from the follwing string

[!DOCTYPE html]
[!--[if IE 8]][html class="no-js lt-ie9" lang="es" ][![endif]--]
[!--[if gt IE 8]][!--] [html class="no-js" lang="es" ] [!--[![endif]--]
[html lang="es-ES" prefix="og: http://ogp.me/ns#"]
[head]

to the above

[!DOCTYPE html][!--[if IE 8]][html class="no-js lt-ie9" lang="es" ][![endif]--]
[!--[if gt IE 8]][!--][html class="no-js" lang="es" ][!--[![endif]--][html lang="es-ES" prefix="og: http://ogp.me/ns#"][head]

clearing all the \r \n \t

\n = new line \r = carriage return \t = tab

EDIT ANSWER

The full answer using UPDATE, SET and REPLACE in addition to Elias Van Ootegem's suggestion

UPDATE tab
SET col = REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(col, '~', ''), 
                '\t', '' -- replace tabs
            ),
            '\n','' -- replace *NIX line-feeds
        ),
        '\r', -- replace DOS line-feeds
        ''
    )
Was it helpful?

Solution

To replace all whitespace chars from any string in mysql, you'll have to call REPLACE a couple of times:

SELECT
    REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(fieldName, ' ', ''), -- replace spaces
                '\t', '' -- replace tabs
            ),
            '\n','' -- replace *NIX line-feeds
        ),
        '\r', -- replace DOS line-feeds
        ''
    );

That should cover them all. If I forgot about one, just add another REPLACE( /*replace calls here*/, '~', ''), to add that to the list.
MySQL isn't that good at processing text, though, so whatever you'll attempt, it'll feel a tad clunky

OTHER TIPS

You can try trim and replace function

UPDATE `table` SET `col_name` = TRIM( `col_name` )

UPDATE `table` SET `col_name` = REPLACE( `col_name` , ' ' , '' )

I hope it may solve the problems

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top