Search code examples
phpexplodetrimcsvsubstring

How to split delimited string with leading and trailing characters to array?


For example, if I have this string:

$stuff = "[1379082600-1379082720],[1379082480-1379082480],[1379514420-1379515800],";

I know can do this to split it into an array like this:

$stuff = str_replace(array("[","]"),array("",""),$stuff);
$stuff = explode(",",$stuff);

But it seems like there would be an easier way since the string is already in an array form almost. Is there an easier way?


Solution

  • You can get inside [] with preg_match_all. Try following:

    preg_match_all("/\[(.*?)\]/",$stuff, $matches);
    

    Output of $matches[1]

    array (size=3)
      0 => string '1379082600-1379082720' (length=21)
      1 => string '1379082480-1379082480' (length=21)
      2 => string '1379514420-1379515800' (length=21)