4

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.

Django Johnson
  • 1,383
  • 3
  • 21
  • 40
  • Does this answer your question? [Split string by white-space](https://stackoverflow.com/questions/23206953/split-string-by-white-space) – ggorlen May 14 '23 at 05:02

4 Answers4

9

Like this:

preg_split('#\s+#', $string, null, PREG_SPLIT_NO_EMPTY);
silkfire
  • 24,585
  • 15
  • 82
  • 105
0
$yourSplitArray=preg_split('/[\ \n\,]+/', $your_string);
Swapnil
  • 592
  • 3
  • 13
0

try this

 preg_split(" +", "hypertext language    programming"); //for one or more whitespaces
sharif2008
  • 2,716
  • 3
  • 20
  • 34
-1

you can see here: PHP explode() Function

<?php
    $str = "Hello world. It's a beautiful day.";
    print_r (explode(" ",$str));
?>

will return:

Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
Eliran Efron
  • 621
  • 5
  • 16