user474470
user474470

Reputation:

Using variables in preg_replace

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.

Upvotes: 0

Views: 238

Answers (1)

deceze
deceze

Reputation: 522635

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

Upvotes: 4

Related Questions