php preg_split将字符串从方括号拆分为数组

I want to split the string from square brackets without removing any character. I tried the below code but it's not working for me.

$value = "<p>&nbsp;Lorem ipsum dolor [State] sit amet, consectetur [City] adipisicing [TopJob7] elit, sed do eiusmod [JobType]</p>";

$tagsReplace = preg_split('/[\[]*[\][]/U', $value, -1);

echo '<pre>';
print_r( $tagsReplace );
exit;

When I run the above code I got the output like

Array
(
    [0] => <p>&nbsp;Lorem ipsum dolor 
    [1] => State
    [2] =>  sit amet, consectetur 
    [3] => City
    [4] =>  adipisicing 
    [5] => TopJob7
    [6] =>  elit, sed do eiusmod 
    [7] => JobType
    [8] => </p>
)

I want output like below.

Array
(
    [0] => <p>&nbsp;Lorem ipsum dolor 
    [1] => [State]
    [2] =>  sit amet, consectetur 
    [3] => [City]
    [4] =>  adipisicing 
    [5] => [TopJob7]
    [6] =>  elit, sed do eiusmod 
    [7] => [JobType]
    [8] => </p>
)

Please help me where I did a mistake.

Your pattern [\[]*[\][] matches 0+ times an opening bracket and then either a opening or closing bracket giving you either a [ or n ]

To keep the delimiters you could capture in a group matching from [ to ] and match what is in between using a negated character class matching not a closing bracket.

Use the PREG_SPLIT_DELIM_CAPTURE flag to keep the delimiter.

Note that you don't need the /U flag.

(\[[^]]+\])

Explanation

  • ( Capturing group
    • \[ Match [
    • [^]]+ Match 1+ times not a ]
    • \] Match ]
  • ) Close group

Regex demo | Php demo

For example:

$value = "<p>&nbsp;Lorem ipsum dolor [State] sit amet, consectetur [City] adipisicing [TopJob7] elit, sed do eiusmod [JobType]</p>";
$tagsReplace = preg_split('/(\[[^]]+\])/', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r( $tagsReplace );