繁体   English   中英

使用preg_match_all进行嵌套模式匹配(Regex和PHP)

[英]Nested pattern matching with preg_match_all (Regex and PHP)

我正在处理包含特殊标志的文本数据,这些标志的形式为“ {X}”或“ {XX}”,其中X可以是任何字母数字字符。 当这些标志相邻或分开时,会为其赋予特殊含义。 我需要一个正则表达式,它将匹配相邻的标志并分隔组中的每个标志。

例如,给定以下输入:

{B}{R}: Target player loses 1 life.
{W}{G}{U}: Target player gains 5 life.

输出应为近似值:

("{B}{R}",
 "{W}{G}{U}")

("{B}",
 "{R}")

("{W}",
 "{G}",
 "{U}")

我的PHP代码正确返回了neighbors数组,但是split数组在每个组中仅包含最后一个匹配标志:

$input = '{B}{R}: Target player loses 1 life.
{W}{G}{U}: Target player gains 5 life.';
$pattern = '#((\{[a-zA-Z0-9]{1,2}})+)#';
preg_match_all($pattern, $input, $results);
print_r($results);

输出:

Array
(
    [0] => Array
        (
            [0] => {B}{R}
            [1] => {W}{G}{U}
        )

    [1] => Array
        (
            [0] => {B}{R}
            [1] => {W}{G}{U}
        )

    [2] => Array
        (
            [0] => {R}
            [1] => {U}
        )

)

谢谢你的帮助!

unset($results[1]);
foreach($results[0] AS $match){
    preg_match_all('/\{[a-zA-Z0-9]{1,2}}/', $match, $r);
    $results[] = $r[0];
}

这是我知道创建所需数据结构的唯一方法。 不过,preg_split也可以工作:

unset($results[1]);
foreach($results[0] AS $match)
    $results[] = preg_split('/(?<=})(?=\{)/', $match);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM