Chris Forrence
Chris Forrence

Reputation: 10104

Regular expression for substitution

I'm working on a way to pass variables into a notification, and to accomplish this, I'm currently going through the message once with the following method:

private static function set($var, $content, &$message) {
    $message = str_replace("{{" . $var . "}}", $content, $message);
}

This correctly matches; if I have '{{name}}' within message and I run the below method, all instances of '{{name}}' are correctly replaced with 'Johnny Test'. Splendid.

self::set('name', 'Johnny Test', $message);

I'm now looking to expand this to allow for the possibility of a template field not being passed into the notification. That is, if I need 'name' and 'email' for a specific notification but only 'name' gets passed in, I want a default value ('No email address') to be passed in (instead of the notification showing '{{email}}').

To this end, I've concocted the following using this tool:

$returnValue = preg_replace(
    '/\\{\\{.*?\\:\\s*?[\'"](.*?)[\'"]\\s*?\\}\\}/',
    '$1', 
    '{{color : "No color selected"}}'
);

However, it doesn't properly match. Instead of $returnValue containing 'No color selected', it instead contains the full-on '{{color : "No color selected"}}'.

What am I missing?

Upvotes: 0

Views: 178

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89629

This should work:

$returnValue = preg_replace(
    '/{{[^:]*:\s*[\'"]([^\'"]*)[\'"]\s*}}/',
    '$1', 
    '{{color : "No color selected"}}'
);

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324780

You have too many backslashes. You're working with single quotes, so \ alone has no special meaning.

Therefore:

'/\{\{.*?:\s*[\'"](.*?)[\'"]\s*\}\}/'

Should do it.

Upvotes: 2

Related Questions