2 /* petite aide suivant une idée héritée de Python */
3 function format_with_dict($str, $dict) {
4 if (!is_array($dict)) {
5 echo "ERROR: second parameter must be a dictionary.\n";
11 $pos = strpos($str, '%', $offset);
12 while ($pos !== false
&& $pos < strlen($str)-1) {
13 $result[] = substr($str, $offset, $pos-$offset);
15 if ($str[$offset-1] == '%') {
17 } elseif ($str[$offset-1] == '(') {
18 // $pos = strpos($str, ')', $offset);
19 for ($pos=$offset;$pos<strlen($str)&&(ctype_alnum($str[$pos])||
$str[$pos]=='_');$pos++
) ;
20 if ($pos < strlen($str)-1 && $str[$pos] == ')') {
21 $var = substr($str, $offset, $pos-$offset);
23 if (isset($dict[$var])) {
24 $result[] = $dict[$var];
26 echo "WARNING: '".$var."' not found in dictionary.\n";
27 $result[] = "%(".$var.")s";
30 echo "ERROR: unterminated format string '".$str."'.\n";
33 } elseif ($str[$offset-1] == 's') {
34 if ($dict_idx < sizeof($dict)) {
35 $result[] = $dict[$dict_idx];
38 echo "WARNING: array index '".$dict_idx."' out of boundary.\n";
42 // if ($str[$offset] != 's') {
43 echo "WARNING: unsupported format type '".$str[$offset-1]."'.\n";
44 $result[] = "%".$str[$offset-1];
46 // $result[] = substr($str, $offset, $pos-$offset);
47 $pos = strpos($str, '%', $offset);
49 $result[] = substr($str, $offset);
50 return implode('', $result);
56 Identité : %(nom_prenom)s
57 Inconnue : %(inconnue)s
64 $dict = Array('nom'=>'A', 'prenom'=>'JC', 'nom_prenom'=>'JCA', 'c1', 'c2');
66 echo format_with_dict($str, $dict);