Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by white-space [duplicate]

Tags:

regex

php

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'];
like image 214
gramme.ninja Avatar asked Oct 14 '25 14:10

gramme.ninja


2 Answers

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
)
like image 133
Quixrick Avatar answered Oct 17 '25 02:10

Quixrick


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
like image 25
zx81 Avatar answered Oct 17 '25 02:10

zx81



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!