Connecting Tech Pros Worldwide Forums | Help | Site Map

How do I remove extra white space in a string?

Newbie
 
Join Date: Jun 2007
Posts: 27
#1: Mar 24 '08
I am currently getting some forecast data from a web site using (file_get_contents), then I'm using explode to put the string in an array, which I am then parsing.

The trouble is when I use explode() are several empty elements between each full one.

Example.
Array ( [0] => this [1] => is [2] => [3] => [4] => a [5] => [6] => [7] => test )

If I print the sting before I explode it I only see one space between each word, but the it seems to be that there is more than one.

Is there a nice php function that will remove all but one white space or does someone have a nice function written which they could show me how to do this.

I understand I can use trim() on the ends but what about extra white space between the words?

thanks

Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,938
#2: Mar 24 '08

re: How do I remove extra white space in a string?


You can use preg_replace to remove whitespace:
[php]
$_subject = "this is a string with whitespace! !";
echo preg_replace('/\s/', ' ', $_subject);
[/php]

Hope this helps :)

Regards
Reply