简体   繁体   English

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

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

I'm working with text data that contains special flags in the form of "{X}" or "{XX}" where X could be any alphanumeric character. 我正在处理包含特殊标志的文本数据,这些标志的形式为“ {X}”或“ {XX}”,其中X可以是任何字母数字字符。 Special meaning is assigned to these flags when they are adjacent or when they are separated. 当这些标志相邻或分开时,会为其赋予特殊含义。 I need a regex which will match adjacent flags AND separate each flag in the group. 我需要一个正则表达式,它将匹配相邻的标志并分隔组中的每个标志。

For Example, given the following input: 例如,给定以下输入:

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

The output should be approximate: 输出应为近似值:

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

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

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

My PHP code is returning the adjacents array properly, but the split array contains only the last matching flag in each group: 我的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);

Output: 输出:

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}
        )

)

Thanks for any help! 谢谢你的帮助!

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

That's the only way I know of to create your Required datastructure. 这是我知道创建所需数据结构的唯一方法。 Though, a preg_split would work as well: 不过,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