简体   繁体   中英

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. 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:

$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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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