私は別の記事で、この非常に疑問答え:vsprintf or sprintf with named arguments, or simple template parsing in PHP
をしかし、これはyoureのを探して同じフォーマットを持っています!
これは実際に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 ...で重大なクエリを作成する場合に特に興味深い使用法です。重複キー更新構文... [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-phpおよびhttp://stackoverflow.com/questions/7435233/name-php-specifiers-in-printf-strings – lqez