php str_replace template with placeholders-Collection of common programming errors

i think it won’t work with str_replace easily so i’m going to use preg_replace

$data = array('title'=>'some title', 'date'=>1350498600, 'story'=>'Some story');
$template = "#title#, 
#date(d)#
#date(m)#
#date(Y)#
#story#"; $result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/', function ($match) use($data) { $value = isset($data[$match[1]]) ? $data[$match[1]] : null; if (!$value) { // undefined variable in template throw exception or something ... } if (! empty($match[2]) && $match[1] == "date") { $value = date($match[2], $value); } return $value; }, $template);

Instead of using date(m) or date(Y) you could also do things like date(d-m-Y) using this snippet

This has the disadvantage that you can format only the date variable using this mechanism. But with a few tweaks you can extend this functionality.

Note: If you use a PHP version below 5.3 you can’t use closures but you can do the following:

function replace_callback_variables($match) {
    global $data; // this is ugly

    // same code as above:

    $value = isset($data[$match[1]]) ? $data[$match[1]] : null;

    if (!$value) {
        // undefined variable in template throw exception or something ...
    }

    if (! empty($match[2]) && $match[1] == "date") {
        $value = date($match[2], $value);
    }
    return $value;
}

$data = array('title'=>'some title', 'date'=>1350498600, 'story'=>'Some story');
$template = "#title#, 
#date(d)#
#date(m)#
#date(Y)#
#story#"; // pass the function name as string to preg_replace_callback $result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/', 'replace_callback_variables', $template);

You can find more information about callbacks in PHP here