Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string by any amount of whitespace in PHP

Tags:

arrays

string

php

I know how to split a string so the words between the delimitor into elements in an array using .explode() by " ".

But that only splits the string by a single whitespace character. How can I split by any amount of whitespace?

So an element in the array end when whitespace is found and the next element in the array starts when the first next non-whitespace character is found.

So something like "The quick brown fox" turns into an array with The, quick, brown, and fox are elements in the returned array.

And "jumped over the lazy dog" also splits so each word is an individual element in the returned array.

like image 289
Django Johnson Avatar asked Oct 21 '25 12:10

Django Johnson


1 Answers

Like this:

preg_split('#\s+#', $string, null, PREG_SPLIT_NO_EMPTY);
like image 172
silkfire Avatar answered Oct 23 '25 03:10

silkfire



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!