【问题标题】:How to remove multiple whitespaces, new lines, carriage return, and tab in a string in MySQL?如何在 MySQL 中删除字符串中的多个空格、新行、回车和制表符?
【发布时间】:2013-10-06 08:47:50
【问题描述】:

您如何使用UPDATESETREPLACEMySQL 中执行以下PHP 函数?

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

来自Remove multiple whitespaces

编辑问题

我的目标是从以下字符串开始

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

\n = 换行 \r = 回车 \t = 制表符

编辑答案

除了 Elias Van Ootegem 的建议之外,使用 UPDATESETREPLACE 的完整答案

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

【问题讨论】:

标签: mysql replace tabs whitespace carriage-return


【解决方案1】:

要从 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 并不擅长处理文本,所以无论你尝试什么,都会觉得有点笨拙

【讨论】:

    【解决方案2】:

    你可以试试修剪和替换功能

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

    希望能解决问题

    【讨论】:

    • 谢谢,我试过了,但是 TRIM 或 REPLACE 不能清除字符串之间的所有空格(\r\n\t)
    • 抱歉,您可以编辑您的答案,以便我给您投票吗?
    猜你喜欢
    • 2014-05-20
    • 1970-01-01
    • 2019-04-19
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多