How can str_replace be effectively used in PHP to replace language variables in a template file?

When working with template files in PHP that contain language variables, we can use the str_replace function to replace these variables with their corresponding values. This allows us to dynamically populate the template with the correct language content based on the user's language preference.

// Define an array of language variables and their corresponding values
$lang = array(
    'welcome_message' => 'Hello, welcome to our website!',
    'contact_us' => 'For any inquiries, please contact us.'
);

// Read the template file into a variable
$template = file_get_contents('template.html');

// Replace language variables in the template with their values
foreach ($lang as $key => $value) {
    $template = str_replace('{' . $key . '}', $value, $template);
}

// Output the modified template
echo $template;