【问题标题】:How to get content from nested mark using PHP with regular expression?如何使用带有正则表达式的 PHP 从嵌套标记中获取内容?
【发布时间】:2013-05-10 11:16:07
【问题描述】:

这是字符串:

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

我想要这个:

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

这是一种 mediawiki 标记格式。一篇文章有​​一个或多个图像标记。

我的代码:

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

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

但我得到了

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

请帮忙!

【问题讨论】:

  • trim($string, '[]'); :)
  • 您需要同时使用 ^ 标记字符串的开头和 $ 标记字符串的结尾。
  • 抱歉,该字符串不是以“[[”开头并以“]]”结尾的。还有更多的字符。我已经编辑了问题。
  • 你想达到什么目的?我怀疑您应该改用 MediaWiki Web API。发明自己的 MediaWiki 标记解析器绝不是一个好主意。 mediawiki.org/wiki/API:Main_page

标签: php regex preg-replace preg-match preg-match-all


【解决方案1】:

您可以使用递归模式来做到这一点:

$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);

解释:

$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

【讨论】:

    【解决方案2】:
    $string = "[[Image:1939.jpg||thumb|right|200px|[[1939]],[[Mr. X]] is [[here]].]]";
    $pattern = '/\[\[(.*)\]\]/';
    
    preg_match($pattern, $string, $result);
    
    var_dump($result);
    

    【讨论】:

    • 对不起,字符串不是以“]]”结尾的。还有更多字符。
    【解决方案3】:

    在你的所有条件下试试这个

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

    【讨论】:

    • 对不起,它不起作用。这是一种 mediawiki 标记格式。一篇文章有​​一个或多个图像标记。
    • 你的意思是喜欢; $text = "aaaadsfasdfaaaa[[Image:1939.jpg||thumb|right|200px|[[1939]],[[Mr. X]] is [[here]].]]bbbbdwebadfaaaaadsfasdfaaaa[[Image:1939.jpg||thumb|right|200px|[[1939]],[[Mr. X]] is [[here]].]]bbbbdwebadfa"?
    猜你喜欢
    • 2011-01-06
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 2013-05-27
    相关资源
    最近更新 更多