gramme.ninja
gramme.ninja

Reputation: 1351

Split string by white-space

How can I split a string by white-space no mater how long the white-space is?

For example, from the following string:

"the    quick brown   fox        jumps   over  the lazy   dog"

I would get an array of

['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'];

Upvotes: 3

Views: 9305

Answers (2)

zx81
zx81

Reputation: 41838

With regex:

$str = "the      quick brown fox jumps over the lazy dog";
$a = preg_split("~\s+~",$str);
print_r($a);

Please note: I modified your string to include a lot of whitespace between the first two words, since this is what you want.

The output:

Array ( [0] => the [1] => quick [2] => brown [3] => fox [4] => jumps [5] => over [6] => the [7] => lazy [8] => dog ) 

How this works:

\s+ means one or more white space characters. It is the delimiter that splits the string. Do note that what PCRE means by "white space characters" is not just the character you obtain by pressing the space bar, but also tabs, vertical tabs, carriage returns and new lines. This should work perfectly for your purpose.

References

  1. For further reading, you may want to have a look at these preg_split examples.
  2. preg_split manual page

Upvotes: 2

Quixrick
Quixrick

Reputation: 3200

You can use Regular Expressions to do this easily:

$string = 'the quick     brown fox      jumps 



over the 

lazy dog';


$words = preg_split('/\s+/', $string, -1, PREG_SPLIT_NO_EMPTY);

print_r($words);

This produces this output:

Array
(
    [0] => the
    [1] => quick
    [2] => brown
    [3] => fox
    [4] => jumps
    [5] => over
    [6] => the
    [7] => lazy
    [8] => dog
)

Upvotes: 11

Related Questions