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

给你一囗甜甜゛ 提交于 2019-11-26 00:09:47

问题


Possible Duplicate:
To strip whitespaces inside a variable in PHP

How can I strip / remove all spaces of a string in PHP?

I have a string like $string = \"this is my string\";

The output should be \"thisismystring\"

How can I do that?


回答1:


Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

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

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

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

(From here).




回答2:


If you want to remove all whitespace:

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

See the 5th example on the preg_replace documentation. (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. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).




回答3:


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);



回答4:


str_replace will do the trick thusly

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


来源:https://stackoverflow.com/questions/2109325/how-do-i-strip-all-spaces-out-of-a-string-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!