Take the 2-minute tour ×

I have a sentence like this.

1 $nbsp; &nbsp; &nbsp; 2 &nbsp; &nbsp; 3 &nbsp; 4

As you see, in between 1 2 and 3 text, there are extra spaces. I want the output with only one space between them. so my output will be 1 2 3 4

How can i use php trim to get the output like this. If i use trim, it can only remove whitespace, but not that  


share|improve this question

4 Answers 4

up vote 5 down vote accepted
$str = "1 $nbsp; &nbsp; &nbsp; 2 &nbsp; &nbsp; 3 &nbsp; 4";
$new_str = str_replace("&nbsp;", '', $str);
share|improve this answer
Thus delegating the work of whitespace stripping to the browser? –  Duncan Mar 26 '10 at 4:39
PHP code is interpreted on the server, not the client. The browser never sees it. –  Peter Gluck May 28 at 7:24

Found this at php.net, works great

trim($str, chr(0xC2).chr(0xA0));

share|improve this answer
Did you notice missing parens? –  Deele Mar 4 '13 at 10:46
@Deele I don't always test my code, but when I do, I do it in production. –  Tobias Fünke Mar 4 '13 at 13:32
Excellent Tobias, thanks a lot... –  Miloš Aug 22 '13 at 13:32
Interesting that the browser actually shows you &nbsp; when the character was just 0xA0. It took me your answer to realize that and fix my bug. –  Alexis Wilke Jun 24 at 7:41
Can also be produced by typing "\xC2\xA0". –  silkfire Nov 10 at 23:22

if your string actually has "  ",

$str="1 &nbsp; &nbsp; &nbsp; 2 &nbsp; &nbsp; 3 &nbsp; 4";
$s = str_replace("&nbsp; ","",$str);
print $s;
share|improve this answer
echo str_replace ( "&nbsp;", "", "1 &nbsp; &nbsp; &nbsp; 2 &nbsp; &nbsp; 3 &nbsp; 4" );

just remember you need to echo out the result of the str_replace and you alo dont need to worry about white spaces a the browser will only show one white space.

share|improve this answer

Your Answer


