php 删除多个空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2326125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:03:16  来源:igfitidea点击:

Remove multiple whitespaces

phpregexstringpreg-replacewhitespace

提问by creativz

I'm getting $row['message']from a MySQL database and I need to remove all whitespace like \n\tand so on.

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

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

should be formatted to:

应格式化为:

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

I tried:

我试过:

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

but it doesn't remove \nor \t, just single spaces. Can anyone tell me how to do that?

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

回答by codaddict

You need:

你需要:

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

You are using \s\s+which means whitespace(space, tab or newline) followed by one or more whitespace. Which effectively means replace two or more whitespace with a single space.

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

What you want is replace one or more whitespace with single whitespace, so you can use the pattern \s\s*or \s+(recommended)

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

回答by Cez

<?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 outputs

这输出

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

回答by Anonymous

preg_replace('/[\s]+/mu', ' ', $var);

\salready contains tabs and new lines, so this above regex appears to be sufficient.

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

回答by Lukas Liesis

simplified to one function:

简化为一个功能:

function removeWhiteSpace($text)
{
    $text = preg_replace('/[\t\n\r
$str='This is   a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);
\x0B]/', '', $text); $text = preg_replace('/([\s])+/', ' ', $text); $text = trim($text); return $text; }

based on Danuel O'Neal answer.

基于 Danuel O'Neal 的回答。

回答by ghostdog74

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

回答by nickf

I can't replicate the problem here:

我无法在这里复制问题:

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

I'm not sure if it was just a transcription error or not, but in your example, you're using a single-quoted string. \nand \tare only treated as new-line and tab if you've got a double quoted string. That is:

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

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

Edit: as Codaddict pointed out, \s\s+won't replace a single tab character. I still don't think using \s+is an efficient solution though, so how about this instead:

编辑:正如 Codacci 指出的那样,\s\s+不会替换单个制表符。我仍然不认为 using\s+是一个有效的解决方案,那么如何改为:

preg_replace('/(\s\s+|\t|\n)/', ' ', $row['message']);

回答by middus

<?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
#    // if it is followed by itself
# +    // one or more

class whitespace{

    static function remove_doublewhitespace($s = null){
           return  $ret = preg_replace('/([\s])+/', ' ', $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
$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;
\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);

This replaces all tabs, all newlines and all combinations of multiple spaces, tabs and newlines with a single space.

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

回答by Danuel O'Neal

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;

回答by hharek

Without preg_replace()

没有 preg_replace()

##代码##

回答by Catalin T.

I use this code and pattern:

我使用这个代码和模式:

##代码##

You may test this on http://writecodeonline.com/php/

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