【问题标题】:Remove multiple whitespaces删除多个空格
【发布时间】:2011-01-20 12:47:25
【问题描述】:

我从 MySQL 数据库中获取 $row['message'],我需要删除所有空格,例如 \n \t 等等。

$row['message'] = "This is   a Text \n and so on \t     Text text.";

应格式化为:

$row['message'] = 'This is a Text and so on Text text.';

我试过了:

 $ro = preg_replace('/\s\s+/', ' ',$row['message']);
 echo $ro;

但它不会删除\n\t,只会删除单个空格。谁能告诉我该怎么做?

【问题讨论】:

  • 换行符和制表符用单引号括起来,所以你想要它们字面意思吗?
  • 我通过将代码段的 \n 和 \t 更改为双引号来修复引用。

标签: php regex string preg-replace whitespace


【解决方案1】:

你需要:

$ro = preg_replace('/\s+/', ' ', $row['message']);

您正在使用\s\s+,这意味着空格(空格、制表符或换行符)后跟一个或多个空格。这实际上意味着用一个空格替换两个或多个空格。

您想要的是用单个空格替换一个或多个空格,因此您可以使用模式\s\s*\s+(推荐)

【讨论】:

  • 他的方法比这个更好:为什么要用一个空格代替一个空格?
  • 他还希望将 \n 和 \t 替换为空格。现在他的模式与这些不匹配,比如 $x = "does\nthis\twork"; OP 希望用单个空格替换所有空格。
  • @codaddict,我们如何保留 \n 并从字符串中删除所有其他多个空格和制表符?请帮帮我
  • 您能否更具体地说明为什么推荐使用“\s+”?
  • 请注意,在 PHP \s 中不包括“垂直标签”chr(11)。要包含它,您还需要使用 space 字符类:[[:space:]]+ php.net/manual/en/regexp.reference.character-classes.php
【解决方案2】:
<?php
$str = "This is  a string       with
spaces, tabs and newlines present";

$stripped = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $str);

echo $str;
echo "\n---\n";
echo "$stripped";
?>

这个输出

This is  a string   with
spaces, tabs and newlines present
---
This is a string with spaces, tabs and newlines present

【讨论】:

  • 你是真正的救星。如果窗户越过这个,我正要跳出去。
  • 简洁,仍然有帮助
【解决方案3】:
preg_replace('/[\s]+/mu', ' ', $var);

\s 已经包含制表符和换行符,所以上面的这个正则表达式似乎就足够了。

【讨论】:

  • 这里不需要方括号,因为里面只有一件事。 /m 不会产生影响,因为没有 ^$ 锚点,/u 不会产生任何影响,除非输入字符串不是有效的 UTF-8(它不会影响 \s 匹配的内容,但会影响 \pZ)。
【解决方案4】:

简化为一个功能:

function removeWhiteSpace($text)
{
    $text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
    $text = preg_replace('/([\s])\1+/', ' ', $text);
    $text = trim($text);
    return $text;
}

基于 Danuel O'Neal 的回答。

【讨论】:

    【解决方案5】:
    $str='This is   a Text \n and so on Text text.';
    print preg_replace("/[[:blank:]]+/"," ",$str);
    

    【讨论】:

    • 这是最适合我的。另外,我会添加修剪以擦除字符串开头和结尾的空格
    • @Dziamid 你可以用 trim(preg_replace(...)) 做到这一点
    【解决方案6】:

    我无法在此处复制问题:

    $x = "this    \n \t\t \n    works.";
    var_dump(preg_replace('/\s\s+/', ' ', $x));
    // string(11) "this works."
    

    我不确定这是否只是转录错误,但在您的示例中,您使用的是单引号字符串。 \n\t 仅在您有双引号字符串时被视为换行符和制表符。那就是:

    '\n\t' != "\n\t"
    

    编辑:正如 Codaddict 指出的那样,\s\s+ 不会替换单个制表符。我仍然不认为使用\s+ 是一个有效的解决方案,所以用这个来代替:

    preg_replace('/(?:\s\s+|\n|\t)/', ' ', $x);
    

    【讨论】:

    • +1,是的。对于具有大量单个空格的字符串(通常是这种情况),用空格替换空格是低效的。
    • @coaddict:为了检验你的假设,我编写了一个快速脚本来运行每个替换的 1000 个并检查每个替换的时间。对于字符串 '+1,True。对于具有大量单个空格的字符串(通常是这种情况),用空格替换空格是低效的。 – codaddict 2 月 24 日 \'10 at 13:32',一千个 \s+ preg_replace() 调用耗时 0.010547876358032 秒,一千个 (?:\s\s+| \n|\t) preg_replace() 调用耗时 0.013049125671387,使其慢了近 30%。
    • 您可能需要在最后一个示例中添加“\r”,因为某些计算机确实单独使用单个“\r”(Apple Mac?)
    【解决方案7】:
    preg_replace('/(\s\s+|\t|\n)/', ' ', $row['message']);
    

    这会用一个空格替换所有制表符、所有换行符以及多个空格、制表符和换行符的所有组合。

    【讨论】:

    • \t & \n 已包含在\s 中,因此您的正则表达式完全\s\s+ 相同,写得更好\s{2,} 就像@亚历克斯·波罗answer
    【解决方案8】:
    <?php
    #This should help some newbies
    # REGEX NOTES FROM DANUEL
    # I wrote these functions for my own php framework
    # Feel Free to make it better
    # If it gets more complicated than this. You need to do more software engineering/logic.
    # (.)  // capture any character
    # \1   // if it is followed by itself
    # +    // one or more
    
    class whitespace{
    
        static function remove_doublewhitespace($s = null){
               return  $ret = preg_replace('/([\s])\1+/', ' ', $s);
        }
    
        static function remove_whitespace($s = null){
               return $ret = preg_replace('/[\s]+/', '', $s );
        }
    
        static function remove_whitespace_feed( $s = null){
               return $ret = preg_replace('/[\t\n\r\0\x0B]/', '', $s);
        }
    
        static function smart_clean($s = null){
               return $ret = trim( self::remove_doublewhitespace( self::remove_whitespace_feed($s) ) );
        }
    }
    $string = " Hey   yo, what's \t\n\tthe sc\r\nen\n\tario! \n";
    echo whitespace::smart_clean($string);
    

    【讨论】:

    • 静态函数remove_whitespace是什么原因?您定义但从不使用它。
    • 这些都有自己的用途,但这些都不能实现问题的要求,即用一个替换多个连续的空格。您的 "remove_doublewhitespace" 只会替换多个 相同 空白字符,因此它会将 "\n\n\n" 替换为 ' ',但它不会对 " \r\n 做任何事情"
    【解决方案9】:

    没有 preg_replace()

    $str = "This is   a Text \n and so on \t     Text text.";
    $str = str_replace(["\r", "\n", "\t"], " ", $str);
    while (strpos($str, "  ") !== false)
    {
        $str = str_replace("  ", " ", $str);
    }
    echo $str;
    

    【讨论】:

      【解决方案10】:

      这是我会使用的:

      一个。确保使用双引号,例如:

      $row['message'] = "This is   a Text \n and so on \t     Text text.";
      

      b.要删除多余的空格,请使用:

      $ro = preg_replace('/\s+/', ' ', $row['message']); 
      echo $ro;
      

      这可能不是最快的解决方案,但我认为它需要的代码最少,而且应该可以工作。不过我从来没用过mysql,所以我可能错了。

      【讨论】:

        【解决方案11】:

        您只需按如下方式运行它:

        echo preg_replace('/\s{2,}/', ' ', "This is   a Text \n and so on \t     Text text."); // This is a Text and so on Text text.
        

        【讨论】:

          【解决方案12】:

          我使用这个代码和模式:

          preg_replace('/\\s+/', ' ',$data)
          
          $data = 'This is   a Text 
             and so on         Text text on multiple lines and with        whitespaces';
          $data= preg_replace('/\\s+/', ' ',$data);
          echo $data;
          

          您可以在 http://writecodeonline.com/php/ 上进行测试

          【讨论】:

          • 在这个查询中,即使在 mariaDB 中它也适用于我:SELECT search_able, REGEXP_REPLACE (search_able,"\\s+",' ') FROM book where id =260 非常感谢
          【解决方案13】:

          事实上,如果你认为你想要这样的东西:

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

          【讨论】:

            【解决方案14】:

            这将用一个标签替换多个标签

            preg_replace("/\s{2,}/", "\t", $string);
            

            【讨论】:

              【解决方案15】:

              这里有两种方法:

              1. str_replace(' ', '', $var);
              2. trim($var);

              您可以自定义trim函数!

              【讨论】:

              • 这将删除所有个空格,甚至那些没有被删除的空格。此外,它不会删除制表符\t 和换行符。
              【解决方案16】:

              不用preg_replace,借助循环。

              <?php
              
              $str = "This is   a Text \n and so on \t     Text text.";
              $str_length = strlen($str);
              $str_arr = str_split($str);
              for ($i = 0; $i < $str_length; $i++) {
                  if (isset($str_arr[$i + 1])
                     && $str_arr[$i] == ' '
                     && $str_arr[$i] == $str_arr[$i + 1]) {
                     unset($str_arr[$i]);
                  } 
                  else {
                    continue;
                  }
              }
              
               echo implode("", $str_arr) ; 
              
               ?>
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2014-02-18
                • 1970-01-01
                • 2012-01-30
                • 2016-05-08
                • 2019-07-06
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多