Django Johnson
Django Johnson

Reputation: 1449

split string by any amount of whitespace in 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.

Upvotes: 4

Views: 3442

Answers (4)

Eliran Efron
Eliran Efron

Reputation: 621

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. )

Upvotes: -1

sharif2008
sharif2008

Reputation: 2798

try this

 preg_split(" +", "hypertext language    programming"); //for one or more whitespaces

Upvotes: 0

silkfire
silkfire

Reputation: 25945

Like this:

preg_split('#\s+#', $string, null, PREG_SPLIT_NO_EMPTY);

Upvotes: 9

Swapnil
Swapnil

Reputation: 616

$yourSplitArray=preg_split('/[\ \n\,]+/', $your_string);

Upvotes: 0

Related Questions