Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php或mysql中去掉多个空格_Php_Mysql - Fatal编程技术网

在php或mysql中去掉多个空格

在php或mysql中去掉多个空格,php,mysql,Php,Mysql,我有一个接受用户输入的表单;最近,我遇到了许多带有多个空格的用户输入。 如。 “我的测试很好!” 有没有办法在PHP或MySQL级别消除这些空白 显然,修剪在这里不起作用 我曾想过使用递归函数,但不确定是否有一种简单快捷的方法 我的代码如下: function noWhiteSpaces($string) { if (!empty($string)) { $string = trim($string); $new_str = str_replace('&nb

我有一个接受用户输入的表单;最近,我遇到了许多带有多个空格的用户输入。 如。 “我的测试很好!” 有没有办法在PHP或MySQL级别消除这些空白

  • 显然,修剪在这里不起作用
  • 我曾想过使用递归函数,但不确定是否有一种简单快捷的方法
  • 我的代码如下:

    function noWhiteSpaces($string) {
       if (!empty($string)) {
          $string = trim($string);
          $new_str = str_replace('  ', ' ', $string);
       } else {
          return false;
       }
       return $new_str;
    }
    
    echo noWhiteSpaces("My        tests     are working fine here       !");
    

    如果输入是实际的空格,并且您希望用单个空格替换它们,则可以使用

    \s
    表示“空白”字符<代码>+表示一个或多个。因此,这将用单个空格替换
    $input
    中一个或多个空白字符的每个实例。看到了,还有一个漂亮的


    如果您不想替换真正的空格,而是想替换像
    这样的东西,那么您也可以这样做,但不能使用
    \s
    。改用这个:

    $stripped = preg_replace('/(&nbsp;)+/', ' ', $input);
    

    请注意,括号中的

    是输入的实际空白(
    \t
    \n
    ,空格等)还是类似于
    ?有一点不同,基本上我已经尝试过preg_替换,类似于你的建议;但这并不能完全消除出现的空白。谢谢@我已经更新了答案。下次请讲清楚。
    $stripped = preg_replace('/(&nbsp;)+/', ' ', $input);