【问题标题】:how to remove space in a sentence in mysql如何在mysql中删除句子中的空格
【发布时间】:2013-01-12 06:16:07
【问题描述】:

有人可以帮助我如何删除我的 sql 中的空格。 例如 假设我输入“I am a good boy”...我希望它在我的 mysql 表列中保存为“iamagoodboy”删除我发送的任何内容的所有空格.. 在下面这段代码中我可以在哪里执行此操作,非常感谢

$sql = 'INSERT INTO messages (username,usernameto, message_content, message_time)      VALUES ("' . $username . '", "' . $messageTo . '", "' . $message . '", ' . $time . ')';

$result = mysql_query($sql, $cn) or

die(mysql_error($cn));

【问题讨论】:

  • 谷歌有什么要说的?
  • 请注意,您的代码无法防止 SQL 注入

标签: php html mysql phpmyadmin


【解决方案1】:
str_replace(' ', '', $message);

在 PHP 中应该可以正常工作。作为一般规则,不要将此类功能放在数据库上,没有理由将负载放在该服务器上 - 而是在 Web 服务器上执行。

所以您的代码将如下所示(假设您从$message 中取出空格):

$sql = 'INSERT INTO messages (username,usernameto, message_content, message_time)      VALUES ("' . $username . '", "' . $messageTo . '", "' . str_replace(' ', '', $message) . '", ' . $time . ')';

不过,更好的解决方案可能是使用preg_replace('/\s+/', '', $string);,它将去除所有空格(制表符、换行符等)。取决于你到底想完成什么。

【讨论】:

    【解决方案2】:

    使用 str_replace:

    $string = str_replace(' ', '', $string);
    

    或删除所有空格

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

    来源:How to strip all spaces out of a string in php?

    【讨论】:

    • preg_replace 示例可能是您想要的,因为它还将替换多个连续的空格、制表符和换行符
    【解决方案3】:

    您可以使用 SQL 替换字符 -> SELECT REPLACE(caption,'\"','\'') FROM ...

    【讨论】:

      【解决方案4】:

      你可以试试这个

       '".str_replace(' ', '', $messageTo)."'
      

      其他也一样

      【讨论】:

        【解决方案5】:
        $sql = 'INSERT INTO messages " . 
        . "(username,usernameto,message_content,message_time) " .
        . "VALUES ("'.$username.'","'.$messageTo.'",REPLACE("'.$message.','' '','''')",'.$time .')';
        
        $result = mysql_query($sql, $cn) or   die(mysql_error($cn));
        

        【讨论】:

          猜你喜欢
          • 2014-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-31
          • 2015-05-03
          • 2016-04-02
          • 2018-12-31
          相关资源
          最近更新 更多