2010-01-21 13:02

如何去掉字符串中的所有空格? [重复]


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?


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • weixin_41568110 七度&光 11年前

    Do you just mean spaces or all whitespace?

    For just spaces, use str_replace:

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

    For all whitespace, use preg_replace:

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

    (From here).

    点赞 27 评论 复制链接分享
  • csdnceshi65 larry*wei 11年前

    str_replace will do the trick thusly

    $new_str = str_replace(' ', '', $old_str);
    点赞 6 评论 复制链接分享
  • weixin_41568134 MAO-EYE 11年前

    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 评论 复制链接分享
  • weixin_41568184 叼花硬汉 11年前

    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);
    点赞 2 评论 复制链接分享