2013-09-30 26 views
-1

如何執行以下操作PHP函數MySQL使用UPDATE,SETREPLACE如何刪除MySQL中的字符串中的多個空格,換行,回車和製表符?

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

Remove multiple whitespaces

編輯問題

我OBJECTIF是從如下字符串

[!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] 

去上述

[!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] 

所有\ r \ n \ t

\ =新線 \ R =回車 \ T =標籤

編輯答案

完整的答案使用UPDATEñ結算,SETREPLACE除了Elias Van Ootegem的建議外

UPDATE tab 
SET col = REPLACE(
     REPLACE(
      REPLACE(
       REPLACE(col, '~', ''), 
       '\t', '' -- replace tabs 
      ), 
      '\n','' -- replace *NIX line-feeds 
     ), 
     '\r', -- replace DOS line-feeds 
     '' 
    ) 
+3

你甚至試過......有這個問題的數以千計的愚蠢:http:// stackoverflow.com/questions/6858143/mysql-how-to-remove-white-space-in-a-mysql-field –

+0

它是沒有我想要的... – RafaSashi

+0

添加的答案,希望這就是你之後 –

回答

2

從MySQL中任何字符串替換所有空格字符,你必須調用REPLACE一對夫婦次:

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

這應該涵蓋所有。如果我忘記了一個,只需添加另一個REPLACE(/*replace calls here*/, '~', '')即可將其添加到列表中。但是,MySQL不擅長處理文本,所以無論你嘗試什麼,它會感覺有點笨拙

0

您可以嘗試修剪和替換功能

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

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

我希望這可以解決問題

+0

謝謝,我試過了,但TRIM或REPLACE並沒有清除字符串 – RafaSashi

+0

之間的所有空格(\ r \ n \ t),對不起,你能編輯你的答案,以便我可以投票給你嗎? – RafaSashi

相關問題