How can PHP functions like sprintf and str_replace be utilized to effectively replace variables in text stored in arrays?

When working with text stored in arrays in PHP, you can use functions like sprintf and str_replace to effectively replace variables within the text. sprintf allows you to format a string with placeholders for variables, while str_replace can be used to replace specific substrings within a string. By combining these functions, you can easily replace variables in text stored in arrays.

$text_array = array(
    'Hello %s, welcome to %s!',
    'Today is %s. Enjoy your %s!'
);

$name = 'John';
$place = 'Stack Overflow';
$day = 'Monday';
$activity = 'coding';

foreach ($text_array as $text) {
    $formatted_text = sprintf($text, $name, $place);
    $final_text = str_replace('%s', $activity, $formatted_text);
    
    echo $final_text . PHP_EOL;
}