0

i have following string in $subject variable

<p>{{headline}}</p>

And i have a variable$headline="Hello World"

As you guess i want to replace {{headline}} With Hello World using preg-replace.

Method must be dynamic, because it's just an example for headline.

2
  • Are you trying to create a templating system? Commented Jun 27, 2013 at 13:31
  • Yep. Something like that Commented Jun 27, 2013 at 13:32

1 Answer 1

4
$vars = array(
    'headline' => 'foo'
);

echo preg_replace_callback('/\{\{(\w+)\}\}/', function (array $m) use ($vars) {
    return $vars[$m[1]];
}, '<p>{{headline}}</p>');

You might really want to look into an existing templating system with a similar syntax but based on a proper parser though, like http://twig.sensiolabs.org. Mustache also basically already does the same thing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.