如何使用带正则表达式的PHP从嵌套标记获取内容?

Here is the string:

$text = "aaaaaaaa[[Image:1939.jpg||thumb|right|200px|[[1939]], [[Mr. X]] is [[here]].]]bbb";

I wanna get this:

Image:1939.jpg||thumb|right|200px|[[1939]],[[Mr. X]] is [[here]].

It's a mediawiki mark format. one article has one or more image mark.

My code:

$pattern = "/\[\[Image:([\s\S]*?)\]\]/";

preg_match($pattern, $text, $match);

But i got

Image:1939.jpg||thumb|right|200px|[[1939

Please help!

You can do it using a recursive pattern:

$pattern = '~\[\[((?>[^[\]]++|(?R))*+)]]~';
$subject = 'aaaaaaaa[[Image:1939.jpg||thumb|right|200px|[[1939]], [[Mr. X]] is [[here]].]]bbb';

preg_match($pattern, $subject, $match);

echo '<pre>' . print_r($match[1], true);

explanation:

$pattern =
  '~               # delimiter of the pattern
   \[\[            # the two open square brackets
   (               # first capture group
     (?>           # atomic group
         [^[\]]++  # all chars except square brackets 1 or more time
       |           # OR
         (?R)      # recurse the whole pattern
     )*+           # end of atomic group 0 or more time (allow void brackets)
   )               # end of capture group
   ]]              # the two closing square brackets
   ~x';            // delimiter with the x modifier that allow comments
$string = "[[Image:1939.jpg||thumb|right|200px|[[1939]],[[Mr. X]] is [[here]].]]";
$pattern = '/\[\[(.*)\]\]/';

preg_match($pattern, $string, $result);

var_dump($result);

try this with your all conditions

$text = "aaaadsfasdfaaaa[[Image:1939.jpg||thumb|right|200px|[[1939]],[[Mr. X]] is [[here]].]]bbbbdwebadfa";
$pattern = "/^[^.]+\[\[(.*)\]\]+[^.]+$/";
preg_match($pattern, $text, $match);
echo $match[1];