Skip to content
PHP Logo

How can regular expressions be used effectively in PHP for replacing variables in templates?

Regular expressions can be used effectively in PHP for replacing variables in templates by using the `preg_replace()` function. This function allows you to search for a specific pattern in a string and replace it with another value. By defining a pattern that matches the variables in your template, you can easily replace them with actual values.

php
$template = "Hello, {name}! Today is {day}.";
$data = [
    'name' => 'John',
    'day' => 'Monday'
];

foreach ($data as $key => $value) {
    $pattern = '/{' . $key . '}/';
    $template = preg_replace($pattern, $value, $template);
}

echo $template;