--- /dev/null
+<?php
+/* petite aide suivant une idée héritée de Python */
+function format_with_dict($str, $dict) {
+ if (!is_array($dict)) {
+ echo "ERROR: second parameter must be a dictionary.\n";
+ return $str;
+ }
+ $result = array();
+ $dict_idx = 0;
+ $offset = 0;
+ $pos = strpos($str, '%', $offset);
+ while ($pos !== false && $pos < strlen($str)-1) {
+ $result[] = substr($str, $offset, $pos-$offset);
+ $offset = $pos + 2;
+ if ($str[$offset-1] == '%') {
+ $result[] = '%';
+ } elseif ($str[$offset-1] == '(') {
+ // $pos = strpos($str, ')', $offset);
+ for ($pos=$offset;$pos<strlen($str)&&(ctype_alnum($str[$pos])||$str[$pos]=='_');$pos++) ;
+ if ($pos < strlen($str)-1 && $str[$pos] == ')') {
+ $var = substr($str, $offset, $pos-$offset);
+ $offset = $pos + 2;
+ if (isset($dict[$var])) {
+ $result[] = $dict[$var];
+ } else {
+ echo "WARNING: '".$var."' not found in dictionary.\n";
+ $result[] = "%(".$var.")s";
+ }
+ } else {
+ echo "ERROR: unterminated format string '".$str."'.\n";
+ $result[] = "%(";
+ }
+ } elseif ($str[$offset-1] == 's') {
+ if ($dict_idx < sizeof($dict)) {
+ $result[] = $dict[$dict_idx];
+ $dict_idx++;
+ } else {
+ echo "WARNING: array index '".$dict_idx."' out of boundary.\n";
+ $result[] = "%s";
+ }
+ } else {
+ // if ($str[$offset] != 's') {
+ echo "WARNING: unsupported format type '".$str[$offset-1]."'.\n";
+ $result[] = "%".$str[$offset-1];
+ }
+ // $result[] = substr($str, $offset, $pos-$offset);
+ $pos = strpos($str, '%', $offset);
+ }
+ $result[] = substr($str, $offset);
+ return implode('', $result);
+}
+/*
+$str = '
+ Nom : %(noms
+ Prenom : %(prenom)s
+ Identité : %(nom_prenom)s
+ Inconnue : %(inconnue)s
+ Résultat : 4%%
+ Champ 1 : %s
+ Champ 2 : %s
+ Champ 3 : %s
+ Fin %d
+';
+$dict = Array('nom'=>'A', 'prenom'=>'JC', 'nom_prenom'=>'JCA', 'c1', 'c2');
+echo "<pre>";
+echo format_with_dict($str, $dict);
+echo "</pre>";
+*/
+?>