Search code examples
mysqlstringphpmyadmintrim

how to remove extra spaces in a sentences inside mysql query


I have a table that contains sentences that might have extra spaces at the beginning, end, or middle of the words. if its in beginning or end of the sentences it is removable using TRIM function but how can I check in between words to remove extra spaces and just leave one

create table messages(sent varchar(200), verif int);
insert into messages values
   ('Hi how are you alex ', null),
   (' Hi alex how are you ', null),
   ('  Hi  alex  how  are    you  ', null);

select * from messages;

UPDATE messages set sent = TRIM(sent);

select * from messages;

here is a demo to understand my situation better Table Demo


Solution

  • Just do a REGEX_REPLACE, something along the lines of:

    select sent,REGEXP_REPLACE(sent,' +',' ') from messages;
    

    which should yield:

    +---------------------------+-------------------------------+
    | sent                      | REGEXP_REPLACE(sent,' +',' ') |
    +---------------------------+-------------------------------+
    | Hi how are you alex       | Hi how are you alex           |
    | Hi alex how are you       | Hi alex how are you           |
    | Hi  alex  how  are    you | Hi alex how are you           |
    +---------------------------+-------------------------------+