数据库字段中的空格不会被trim() 删除 [英] Whitespace in a database field is not removed by trim()

查看:43
本文介绍了数据库字段中的空格不会被trim() 删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MySQL 文本字段的段落开头有一些空格.

在 PHP 中使用 trim($var_text_field) 或在 MySQL 语句中使用 TRIM(text_field) 绝对没有任何作用.这个空格是什么,我如何通过代码删除它?

如果我进入数据库并退格它,它会正确保存.它只是没有通过 trim() 函数删除.

解决方案

function UberTrim($s) {$s = preg_replace('/\xA0/u', ' ', $s);//去除 UTF-8 NBSP: "\xC2\xA0"$s = 修剪($s);返回 $s;}

不间断空格 Unicode (U+00A0) 的 UTF-8 字符编码是 无 BOM.或者在首选项中设置.

  • 确保您的 MySQL 客户端设置为 UTF-8 字符编码(更多此处此处),例如

    $pdo = new PDO('mysql:host=...;dbname=...;charset=utf8',$userid,$password);$pdo->exec("SET CHARACTER SET utf8");

  • 确保您的 HTTP 服务器设置为 UTF-8,例如对于 Apache:

    AddDefaultCharset UTF-8

  • 确保浏览器需要 UTF-8.

    header('Content-Type: text/html; charset=utf-8');

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

  • I have some whitespace at the begining of a paragraph in a text field in MySQL.

    Using trim($var_text_field) in PHP or TRIM(text_field) in MySQL statements does absolutely nothing. What could this whitespace be and how do I remove it by code?

    If I go into the database and backspace it out, it saves properly. It's just not being removed via the trim() functions.

    解决方案

    function UberTrim($s) {
        $s = preg_replace('/\xA0/u', ' ', $s);  // strips UTF-8 NBSP: "\xC2\xA0"
        $s = trim($s);
        return $s;
    }
    

    The UTF-8 character encoding for a no-break space, Unicode (U+00A0), is the 2-byte sequence C2 A0. I tried to make use of the second parameter to trim() but that didn't do the trick. Example use:

    assert("abc" === UberTrim("  \r\n  \xc2\xa0  abc  \t \xc2\xa0   "));
    


    A MySQL replacement for TRIM(text_field) that also removes UTF no-break spaces, thanks to @RudolfRein's comment:

    TRIM(REPLACE(text_field, '\xc2\xa0', ' '))
    


    UTF-8 checklist:

    (more checks here)

    1. Make sure your PHP source code editor is in UTF-8 mode without BOM. Or set in the preferences.

    2. Make sure your MySQL client is set for UTF-8 character encoding (more here and here), e.g.

      $pdo = new PDO('mysql:host=...;dbname=...;charset=utf8',$userid,$password); $pdo->exec("SET CHARACTER SET utf8");

    3. Make sure your HTTP server is set for UTF-8, e.g. for Apache:

      AddDefaultCharset UTF-8

    4. Make sure the browser expects UTF-8.

      header('Content-Type: text/html; charset=utf-8');

      or

      <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

    这篇关于数据库字段中的空格不会被trim() 删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆