本文翻译自:How do I strip all spaces out of a string in PHP? [duplicate]
Possible Duplicate: 可能重复:
To strip whitespaces inside a variable in PHP 在PHP中去除变量内的空格
How can I strip / remove all spaces of a string in PHP? 我怎么能剥夺 / 删除 PHP 字符串的所有空间 ?
I have a string like $string = "this is my string";
我有一个字符串,如$string = "this is my string";
The output should be "thisismystring"
输出应该是"thisismystring"
How can I do that? 我怎样才能做到这一点?
#1楼
参考:https://stackoom.com/question/8qjN/如何在PHP中删除字符串中的所有空格-重复
#2楼
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);
#3楼
If you want to remove all whitespace: 如果要删除所有空格:
$str = preg_replace('/\\s+/', '', $str);
See the 5th example on the preg_replace documentation . 请参阅preg_replace文档中的第5个示例。 (Note I originally copied that here.) (注意我最初在这里复制了。)
Edit: commenters pointed out, and are correct, that str_replace
is better than preg_replace
if you really just want to remove the space character. 编辑:评论者指出,并且是正确的,如果你真的只想删除空格字符, str_replace
比preg_replace
更好。 The reason to use preg_replace
would be to remove all whitespace (including tabs, etc.). 使用preg_replace
的原因是删除所有空格(包括制表符等)。
#4楼
str_replace会这样做
$new_str = str_replace(' ', '', $old_str);
#5楼
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);