Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL : how to remove double or more spaces from a string?

Tags:

string

mysql

I couldn't find this question for MySQL so here it is:

I need to trim all double or more spaces in a string to 1 single space.

For example: "The   Quick  Brown    Fox" should be : "The Quick Brown Fox"

The function REPLACE(str, "  ", " ") only removes double spaces, but leaves multiples spaces when there are more...

like image 478
Dylan Avatar asked Aug 04 '11 11:08

Dylan


4 Answers

Here's an old trick that does not require regular expressions or complicated functions.

You can use the replace function 3 times to handle any number of spaces, like so:

REPLACE('This is    my   long    string',' ','<>')

becomes:

This<>is<><><><>my<><><>long<><><><>string

Then you replace all occurrences of '><' with an empty string '' by wrapping it in another replace:

REPLACE(
  REPLACE('This is    my   long    string',' ','<>'),
    '><',''
)

This<>is<>my<>long<>string

Then finally one last replace converts the '<>' back to a single space

REPLACE(
  REPLACE(
    REPLACE('This is    my   long    string',
      ' ','<>'),
    '><',''),
  '<>',' ')

This is my long string

This example was created in MYSQL (put a SELECT in front) but works in many languages.

Note that you only ever need the 3 replace functions to handle any number of characters to be replaced.

like image 74
xytyx Avatar answered Oct 16 '22 15:10

xytyx


The shortest and, surprisingly, the fastest solution:

CREATE FUNCTION clean_spaces(str VARCHAR(255)) RETURNS VARCHAR(255)
BEGIN
    while instr(str, '  ') > 0 do
        set str := replace(str, '  ', ' ');
    end while;
    return trim(str);
END
like image 31
alkoln Avatar answered Oct 16 '22 17:10

alkoln


I know this question is tagged with mysql, but if you're fortunate enough to use MariaDB you can do this more easily:

SELECT REGEXP_REPLACE(column, '[[:space:]]+', ' ');
like image 22
tomconnors Avatar answered Oct 16 '22 15:10

tomconnors


DELIMITER //

DROP FUNCTION IF EXISTS DELETE_DOUBLE_SPACES//
CREATE FUNCTION DELETE_DOUBLE_SPACES ( title VARCHAR(250) )
RETURNS VARCHAR(250) DETERMINISTIC
BEGIN
    DECLARE result VARCHAR(250);
    SET result = REPLACE( title, '  ', ' ' );
    WHILE (result <> title) DO 
        SET title = result;
        SET result = REPLACE( title, '  ', ' ' );
    END WHILE;
    RETURN result;
END//
DELIMITER ;

SELECT DELETE_DOUBLE_SPACES('a    b');
like image 17
Артур Курицын Avatar answered Oct 16 '22 16:10

Артур Курицын