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...
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.
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
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:]]+', ' ');
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With