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

本文翻译自: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);

(From here ). (从这里开始 )。


#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_replacepreg_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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值