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

前端 未结 11 1319
南方客
南方客 2020-12-03 08:12

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  

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 08:37

    After searching I end up writing a function i.e

    drop function if exists trim_spaces;

    delimiter $$
    
    CREATE DEFINER=`root`@`localhost` FUNCTION `trim_spaces`(`dirty_string` text, `trimChar` varchar(1))
        RETURNS text
        LANGUAGE SQL
        NOT DETERMINISTIC
        CONTAINS SQL
        SQL SECURITY DEFINER
        COMMENT ''
    BEGIN
      declare cnt,len int(11) ;
      declare clean_string text;
      declare chr,lst varchar(1);
    
      set len=length(dirty_string);
      set cnt=1;  
      set clean_string='';
    
     while cnt <= len do
          set  chr=right(left(dirty_string,cnt),1);           
    
          if  chr <> trimChar OR (chr=trimChar AND lst <> trimChar ) then  
              set  clean_string =concat(clean_string,chr);
          set  lst=chr;     
         end if;
    
         set cnt=cnt+1;  
      end while;
    
      return clean_string;
    END
    $$
    delimiter ;
    

    USAGE:

    set @str='------apple--------banana-------------orange---' ;

    select trim_spaces( @str,'-')

    output: apple-banana-orange-

    parameter trimChar to function could by any character that is repeating and you want to remove .

    Note it will keep first character in repeating set

    cheers :)

提交回复
热议问题