关于PHP Split

Can anyone explain me this code split("[ ]+", $s); thanks

 $s = "Split this sentence by spaces";
$words = split("[ ]+", $s);
print_r($words);

Output:
Array
(
    [0] => Split
    [1] => this
    [2] => sentence
    [3] => by
    [4] => spaces
)

Split string into array by regular expression. This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

I reccommend 'explode' function instead 'split':

$s = "Split this sentence by spaces";
$words = explode(" ", $s);
print_r($words);

Output:

array(5) {
 [0]=>
 string(5) "Split"
 [1]=>
 string(4) "this"
 [2]=>
 string(8) "sentence"
 [3]=>
 string(2) "by"
 [4]=>
 string(6) "spaces"
}

It splits the given string into an array by the regular expression "[ ]+" which matches one or more spaces. It could technically just be " +" but since its a space, it is more readable with the brackets.

Note that the split function has been depreciated since version 5.3, and you should use preg_split instead.

It's all in the documentation.

split's first argument is a regular expression which describes what the delimiter looks like. In your case, "[ ]+" (which can also be written simply as " +") means "one or more spaces".

"[ ]+"

Is a regex expression. It will split the string according to spaces.

The first argument to split is a regex pattern, which in this instance is effectively saying "match the space character as many times as possible".

N.B.: split is deprecated as of PHP 5.3, so I wouldn't recommend using this.

You could achieve precisely the same effect via:

$words = explode(" ", $s);

See the explode manual page for more info.

The split function can take regular expression as its argument too. In your case, you specify [ ]+ which means:

[ ]   // a character class is used with a space
 +    // find one or more instances of space

Hence, when you do:

$words = split("[ ]+", $s);

An array is created and stored in $words variable with all letters delimited by space.

More Info:


Note that split function is deprecated. You can do the same things with explode like this:

$s = "Split this sentence by spaces";
$words = explode(' ', $s);
print_r($words);

a good resource for perl regular expressions can be found here.