You can use preg_split
for this as:
$input ='first [abc] middle [xyz] last';
$arr = preg_split('/\[.*?\]/',$input);
print_r($arr);
Output:
Array
(
[0] => first
[1] => middle
[2] => last
)
This allows some surrounding spaces in the output. If you don't want them you can use:
$arr = preg_split('/\s*\[.*?\]\s*/',$input);
preg_split
splits the string based on a pattern. The pattern here is [
followed by anything followed by ]
. The regex to match anything is .*
. Also [
and ]
are regex meta char used for char class. Since we want to match them literally we need to escape them to get \[.*\]
. .*
is by default greedy and will try to match as much as possible. In this case it will match abc] middle [xyz
. To avoid this we make it non greedy by appending it with a ?
to give \[.*?\]
. Since our def of anything here actually means anything other than ]
we can also use \[[^]]*?\]
EDIT:
If you want to extract words that are both inside and outside the []
, you can use:
$arr = preg_split('/\[|\]/',$input);
which split the string on a [
or a ]