我回答在另一篇文章過這個問題:vsprintf or sprintf with named arguments, or simple template parsing in PHP
但是,這您是在尋找相同的格式!
這真的是最好的方式去imho。沒有神祕的字符,只需使用鍵名!
由於從PHP的網站採取: 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
如果您想使用MySQL的_INSERT構建廣泛的查詢,那麼這有一個特別有趣的用法... ON DUPLICATE KEY UPDATE語法..._ [http://dev.mysql.com/doc/refman/5.0/en /insert-on-duplicate.html](http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html) –
請參閱:http://stackoverflow.com/questions/ 5701985/vsprintf-or-sprintf-with-named-arguments-or-simple-tempalte-parsing-in-php and http://stackoverflow.com/questions/7435233/name-php-specifiers-in-printf-strings – lqez