删除多个空格

cre*_*ivz 196 php regex string whitespace preg-replace

$row['message']从MySQL数据库获取,我需要删除所有的空白\n \t,等等.

$row['message'] = "This is   a Text \n and so on \t     Text text.";
Run Code Online (Sandbox Code Playgroud)

应格式化为:

$row['message'] = 'This is a Text and so on Text text.';
Run Code Online (Sandbox Code Playgroud)

我试过了:

 $ro = preg_replace('/\s\s+/', ' ',$row['message']);
 echo $ro;
Run Code Online (Sandbox Code Playgroud)

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

cod*_*ict 376

你需要:

$ro = preg_replace('/\s+/', ' ',$row['message']);
Run Code Online (Sandbox Code Playgroud)

您使用的\s\s+是空格(空格,制表符或换行符),后跟一个或多个空格.这实际上意味着用一个空格替换两个或更多个空格.

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

  • 他还希望用空格替换\n和\ t.现在他的模式与这些模式不匹配,比如$ x ="do \nthis\twork"; OP希望用一个空格替换所有空格. (15认同)
  • 请注意,在PHP`\s`中不包括"vertical tab"`chr(11)`.要包含它,你需要使用`space`字符类:`[[:space:]] +`http://www.php.net/manual/en/regexp.reference.character-classes.php (4认同)
  • 他的方法比这个更好:你为什么要用一个空格替换一个空格? (2认同)

Cez*_*Cez 65

<?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";
?>
Run Code Online (Sandbox Code Playgroud)

这输出

This is  a string   with
spaces, tabs and newlines present
---
This is a string with spaces, tabs and newlines present
Run Code Online (Sandbox Code Playgroud)

  • 你是一个真正的救星。如果窗外那边,我正要跳出来。 (3认同)

Ano*_*ous 14

preg_replace('/[\s]+/mu', ' ', $var);
Run Code Online (Sandbox Code Playgroud)

\s 已包含制表符和新行,因此上面的正则表达式似乎已足够.

  • 这里不需要方括号,因为其中只有一件事。/ m不会有效果,因为没有`^`或`$`锚,`/ u`不会有任何效果,除非稍微降低速度并在输入字符串无效的UTF-时死掉。 8(它不影响`\ s`匹配的内容,但会影响`\ pZ`)。 (2认同)

Luk*_*kas 11

简化为一个功能:

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

根据Danuel O'Neal的回答.


gho*_*g74 7

$str='This is   a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);
Run Code Online (Sandbox Code Playgroud)

  • 这是最适合我的那个.另外,我会添加修剪以删除字符串开头和结尾的空格 (2认同)

nic*_*ckf 7

我不能在这里复制问题:

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

我不确定它是否只是一个转录错误,但在你的例子中,你使用的是单引号字符串.如果您有双引号字符串\n,\t则仅被视为换行符和制表符.那是:

'\n\t' != "\n\t"
Run Code Online (Sandbox Code Playgroud)

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

preg_replace('/(?:\s\s+|\n|\t)/', ' ', $x);
Run Code Online (Sandbox Code Playgroud)

  • +1,真的.对于具有大量单个空格的字符串(通常就是这种情况),用空格替换空间效率很低. (2认同)
  • @coaccin:为了测试你的假设,我写了一个快速脚本来运行每个替换的 1000 次并检查每个替换的时间。对于字符串 **'+1,True。对于具有大量单个空格的字符串(通常是这种情况),用空格替换空格是低效的。– codacci 2 月 24 日 \'10 在 13:32'**,一千次 **\s+** preg_replace() 调用耗时 0.010547876358032 秒,一千次 **(?:\s\s+|\n|\t) ** preg_replace() 调用耗时 0.013049125671387,使其慢了近 30%。 (2认同)

mid*_*dus 5

preg_replace('/(\s\s+|\t|\n)/', ' ', $row['message']);
Run Code Online (Sandbox Code Playgroud)

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


Dan*_*eal 5

<?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);
Run Code Online (Sandbox Code Playgroud)

  • 静态函数 remove_whitespace 是出于什么原因?你定义但从不使用它。 (2认同)