如何在PHP中删除字符串中的所有空格? [重复]

问题描述 投票:555回答:4

可能重复: To strip whitespaces inside a variable in PHP

如何在PHP中删除/删除字符串的所有空格?

我有像$string = "this is my string";这样的字符串

输出应该是"thisismystring"

我怎样才能做到这一点?

php string spaces
4个回答
1272
投票

你只是指空间或所有空格吗?

对于空间,请使用str_replace

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

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

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

(来自here)。


51
投票

如果要删除所有空格:

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

请参阅the preg_replace documentation上的第5个示例。 (注意我最初在这里复制了。)

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


31
投票

如果您知道空白区域仅由空格所致,您可以使用:

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

但如果它可能是由于空间,标签......您可以使用:

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

15
投票

str_replace将这样做

$new_str = str_replace(' ', '', $old_str);
© www.soinside.com 2019 - 2024. All rights reserved.