如何从 PHP 中的字符串中去除所有空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2109325/
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 05:03:22  来源:igfitidea点击:

How do I strip all spaces out of a string in PHP?

phpstringspaces

提问by streetparade

How can I strip/ removeall spacesof a stringin PHP?

我怎么能剥夺/删除所有空格一个的字符串在PHP?

I have a stringlike $string = "this is my string";

我有一个字符串$string = "this is my string";

The output should be "thisismystring"

输出应该是 "thisismystring"

How can I do that?

我怎样才能做到这一点?

回答by Mark Byers

Do you just mean spaces or all whitespace?

你是指空格还是所有空格?

For just spaces, use str_replace:

对于空格,请使用str_replace

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

For all whitespace (including tabs and line ends), use preg_replace:

对于所有空格(包括制表符和行尾),请使用preg_replace

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

(From here).

(从这里)。

回答by Arkaaito

If you want to remove all whitespace:

如果要删除所有空格:

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

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

See the 5th example on the preg_replace documentation. (Note I originally copied that here.)

请参阅preg_replace 文档中的第 5 个示例。(注意我最初是在这里复制的。)

Edit: commenters pointed out, and are correct, that str_replaceis better than preg_replaceif you really just want to remove the space character. The reason to use preg_replacewould be to remove all whitespace (including tabs, etc.).

编辑:评论者指出并且是正确的,这str_replacepreg_replace您真的只想删除空格字符要好。使用的原因preg_replace是删除所有空格(包括制表符等)。

回答by codaddict

If you know the white space is only due to spaces, you can use:

如果您知道空白仅由空格引起,则可以使用:

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

But if it could be due to space, tab...you can use:

但是,如果可能是由于空间原因,请使用制表符...您可以使用:

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

回答by David Heggie

str_replacewill do the trick thusly

str_replace将这样做

$new_str = str_replace(' ', '', $old_str);