-1
$string = "[john] sometext [rohn] sometext [mohan]";

How to get the data between square brackets each in different array.

I have below code

preg_match_all("/\((?:[^()]|(?R))+\)/",  $string , $matches);

above code works perfect for curly bracket in the way i need, but how to make it work for square brackets?

Habib
  • 591
  • 8
  • 29

1 Answers1

0
$string = "[john] sometext [rohn] sometext [mohan]";
preg_match_all("/\[([^]]+)\]/",  $string , $matches);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => [john]
            [1] => [rohn]
            [2] => [mohan]
        )

    [1] => Array
        (
            [0] => john
            [1] => rohn
            [2] => mohan
        )

)

Explanation:

\[          : opening square bracket
(           : start group 1
    [^]]+   : 1 or more any character that is not closing square bracket
)           : end group 1
\]          : closing square racket
Toto
  • 89,455
  • 62
  • 89
  • 125