user1032531
user1032531

Reputation: 26281

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

Upvotes: 0

Views: 44

Answers (3)

georg
georg

Reputation: 214949

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;

Upvotes: 1

Peter Pei Guo
Peter Pei Guo

Reputation: 7870

Try this:

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

Upvotes: 1

Cheery
Cheery

Reputation: 16214

Something like this (did not check it) /\{("|\'){\ (\w+)\ \}\1/ or /\{(["\']){\ (\w+)\ \}\1/

Upvotes: 1

Related Questions