dongpang4470
dongpang4470
2013-05-10 11:16

如何使用带正则表达式的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!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doushai7225 doushai7225 8年前

    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
    
    点赞 评论 复制链接分享
  • dongyang7152 dongyang7152 8年前

    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];
    
    点赞 评论 复制链接分享
  • dongxian0421 dongxian0421 8年前
    $string = "[[Image:1939.jpg||thumb|right|200px|[[1939]],[[Mr. X]] is [[here]].]]";
    $pattern = '/\[\[(.*)\]\]/';
    
    preg_match($pattern, $string, $result);
    
    var_dump($result);
    
    点赞 评论 复制链接分享