lafif-a
11/24/2014 - 5:52 AM

[PHP] Replace string to variable with pattern

[PHP] Replace string to variable with pattern

<?php 
/**
 * Replace string with pattern 
 * (example use: for mail templating)
 * 
 * @codes array(); 
 * @pattern string; 
 */

$message = 'coba username {username} atau {user_email}';
    
$codes = array(
	'username' => $username,
	'user_email' => $email
);

$pattern = '{%s}'; 

$map = array();
foreach($codes as $var => $value) {
    $map[sprintf($pattern, $var)] = $value;
}

$message = strtr($message, $map);

echo $message;
?>