I answered this question in another post: vsprintf or sprintf with named arguments or simple template analysis in PHP
But this is the same format you are looking for!
This is really the best way to go IMHO. No critical characters, just use key names!
As taken from php site: http://www.php.net/manual/en/function.vsprintf.php
function dsprintf() { $data = func_get_args(); // get all the arguments $string = array_shift($data); // the string is the first one if (is_array(func_get_arg(1))) { // if the second one is an array, use that $data = func_get_arg(1); } $used_keys = array(); // get the matches, and feed them to our function $string = preg_replace('/\%\((.*?)\)(.)/e', 'dsprintfMatch(\'$1\',\'$2\',\$data,$used_keys)',$string); $data = array_diff_key($data,$used_keys); // diff the data with the used_keys return vsprintf($string,$data); // yeah! } function dsprintfMatch($m1,$m2,&$data,&$used_keys) { if (isset($data[$m1])) { // if the key is there $str = $data[$m1]; $used_keys[$m1] = $m1; // dont unset it, it can be used multiple times return sprintf("%".$m2,$str); // sprintf the string, so %s, or %d works like it should } else { return "%".$m2; // else, return a regular %s, or %d or whatever is used } } $str = <<<HITHERE Hello, %(firstName)s, I know your favorite PDA is the %(pda)s. You must have bought %(amount)s HITHERE; $dataArray = array( 'pda' => 'Newton 2100', 'firstName' => 'Steve', 'amount' => '200' ); echo dsprintf($str, $dataArray); // Hello, Steve, I know your favorite PDA is the Newton 2100. You must have bought 200
source share