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'];
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
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With