Search code examples
phpregexsplitsquare-bracketcharacter-class

What special meaning do square braces have in a regular expression?


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
)

Solution

  • 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"
    }