How do I remove extra white space in a string?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bdbeames
    New Member
    • Jun 2007
    • 27

    How do I remove extra white space in a string?

    I am currently getting some forecast data from a web site using (file_get_conte nts), 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
    Recognized Expert Expert
    • Jun 2007
    • 6092

    #2
    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

    Comment

    Working...