可能重复:在PHP中去除变量内的空格
我怎么能在PHP中 string string 的所有 spaces ?
我有 string 喜欢 $string = "this is my string"; 输出应该是 "thisismystring"
$string = "this is my string";
"thisismystring"
我怎样才能做到这一点?
你只是指空间或所有空格吗?
对于空格,请使用str_replace:
$string = str_replace(' ', '', $string);
对于所有空格,请使用preg_replace:
$string = preg_replace('/\s+/', '', $string);
(来自here) .
如果要删除所有空格:
$str = preg_replace('/\s+/', '', $str);
请参阅the preg_replace documentation上的第5个示例 . (注意我最初在这里复制了 . )
编辑:评论者指出,并且是正确的,如果你真的只想删除空格字符,那么 str_replace 优于 preg_replace . 使用 preg_replace 的原因是删除所有空格(包括制表符等) .
str_replace
preg_replace
str_replace会这样做
$new_str = str_replace(' ', '', $old_str);
如果您知道空白区域仅由空格所致,您可以使用:
$string = str_replace(' ','',$string);
但如果它可能是由于空间,标签......您可以使用:
$string = preg_replace('/\s+/','',$string);
4 回答
你只是指空间或所有空格吗?
对于空格,请使用str_replace:
对于所有空格,请使用preg_replace:
(来自here) .
如果要删除所有空格:
$str = preg_replace('/\s+/', '', $str);
请参阅the preg_replace documentation上的第5个示例 . (注意我最初在这里复制了 . )
编辑:评论者指出,并且是正确的,如果你真的只想删除空格字符,那么
str_replace
优于preg_replace
. 使用preg_replace
的原因是删除所有空格(包括制表符等) .str_replace会这样做
如果您知道空白区域仅由空格所致,您可以使用:
但如果它可能是由于空间,标签......您可以使用: