简体   繁体   中英

Regular expressions using two separate patterns

I have a function that parses some text, and replaces any tags that are surrounded by "{ and }" with values in an array.

function parse($template, array $values) {
    return preg_replace_callback('/\{"{\ (\w+)\ \}\"/',function ($matches) use ($values) {
        return isset($values[$matches[1]])?$values[$matches[1]]:$matches[0];
        },
        $template);
}

How can it be modified to do the same, but also use a second deliminator? Specifically, I also which it to replace tags surrounded by '{ and }'

尝试这个:

/\{['"]{\ (\w+)\ \}['"]/

这样的东西(没有检查) /\\{("|\\'){\\ (\\w+)\\ \\}\\1//\\{(["\\']){\\ (\\w+)\\ \\}\\1/

A better option is to list possible delimiters explicitly:

$re = <<<RE
/
    "{ (\w+) }"
    |
    '{ (\w+) }'
/x
RE;

(using extended syntax for readability). The actual captured group will be at the end of the matches array:

preg_replace_callback($re, function ($matches) use ($values) {
        $word = end($matches);
        if (isset($values[$word])) etc....
},

This verbosity will pay off once you introduce more delimiters, especially non-symmetric ones, for example:

$re = <<<RE
/
    "{ (\w+) }"
    |
    '{ (\w+) }'
    |
    <{ (\w+) }>
    |
    {{ (\w+) }}
/x
RE;

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