Search code examples
phppreg-split

Compilation failed: missing terminating ] for character class


$date could be "23/09/2012" or "23-09-2012" or "23\09\2012" 
preg_split('/[\/\-\\]/', $date);

Not sure why PHP keep throw missing terminating ] error?


Solution

  • preg_split('/[\/\-\\]/', $date);
                       ^escaping the closing ']' 
    

    Do the following instead, to remove ambiguity

    preg_split('/[\/\-\\\\]/', $date);
    

    There is no need to escape -, but you could use \- as well.


    Code:

    $date = 'as\sad-s/p';
    $slices =  preg_split('/[\/\-\\\\]/', $date);
    print_r($slices);
    

    Output:

    Array ( [0] => as [1] => sad [2] => s [3] => p )