Split on alternative between [
and ]
, and use the flag PREG_SPLIT_NO_EMPTY
to not catch empty parts.
$str = "[10:42-23:10]part1[11:30-13:20]part2";
$parts = preg_split("/\[|\]/", $str, -1, PREG_SPLIT_NO_EMPTY );
print_r($parts);
Output:
Array
(
[0] => 10:42-23:10
[1] => part1
[2] => 11:30-13:20
[3] => part2
)
NB.
Thank to @WiktorStribiżew , his regex /[][]/
is much more efficient, I've some benchmark, it is about 40% faster.
$str = "[10:42-23:10]part1[11:30-13:20]part2";
$parts = preg_split("/[][]/", $str, -1, PREG_SPLIT_NO_EMPTY );
print_r($parts);
Here is the perl script I have used to do the benchmark:
#!/usr/bin/perl
use Benchmark qw(:all);
my $str = "[10:42-23:10]part1[11:30-13:20]part2";
my $count = -5;
cmpthese($count, {
'[][]' => sub {
my @parts = split(/[][]/, $str);
},
'\[|\]' => sub {
my @parts = split(/\[|\]/, $str);
},
});
Result: (2 runs)
>perl -w benchmark.pl
Rate \[|\] [][]
\[|\] 536640/s -- -40%
[][] 891396/s 66% --
>Exit code: 0
>perl -w benchmark.pl
Rate \[|\] [][]
\[|\] 530867/s -- -40%
[][] 885242/s 67% --
>Exit code: 0