1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
$arbre = new Newik( '((((1:0.a1,2:a2)3:0.a3,((4:0.b1,5:0.b2)6:0.b3,(7:0.c1,8:0.c2)9:0.c3)10:0.bc3)11:0.abc3,(12:0.d1,13:0.d2):0.d3)14:0.abcd3,15:0.e2)');
$foobar = null;
echo '<pre>';
print_r($arbre->parse($arbre));
Class Newik {
protected $arbre;
private $position;
private $max_leng;
function __construct($arbre){
$this->arbre = $arbre;
$this->init();
}
function init(){
$this->position=0;
$this->max_leng = strlen($this->arbre);
}
function debug($msg, $tampon, $flag){
echo $this->arbre,"\n";
$turing = str_repeat('.',$this->max_leng)."\n";
$turing[$this->position]= "^";
echo $turing;
echo $msg,' ',$this->arbre[$this->position],' position:',$this->position,' tampon:',$tampon,' flag:',$flag,"\n\n";
}
function appendChild(&$resultat, $flag,$tampon){
// $this->debug('naming ', $tampon, $flagNomGroupe );
if ( $flag == 2 ){
$last = array_pop($resultat);
$resultat[$tampon]=$last;
}
else {
$resultat[]=$tampon;
}
}
function parse(){
// $this->debug(' begin ', $arbre, $position );
$tampon = '';
$resultat=array();
$flagNomGroupe = 0; // a 2 lorsque ce qui suit peut être un nom de sous groupe.
while( $this->position < $this->max_leng ){
$tmp = $this->arbre[$this->position];
if( $tmp == '(' ) {
//$this->debug('open ', $tampon,$flagNomGroupe );
$this->position++;
$resultat[]= $this->parse(); //passage par référence!
$flagNomGroupe = 1; //d'apres wikipedia, on peut avoir un nom de groupe apres une ), dans ce cas pas de ,
}
else if ($tmp == ')') {
//on a fini de lire le fils de droite
$this->appendChild($resultat, $flagNomGroupe, $tampon);
//$this->debug('closing ', $tampon,$flagNomGroupe );
return $resultat;
}
else if( $tmp == ',' ) {
// on a fini de lire le fils de gauche
$this->appendChild($resultat, $flagNomGroupe, $tampon);
if ( $flagNomGroupe == 1 ){ //une virgule tout de suite après une ')'
$flagNomGroupe = 0;
}
$tampon = '';
}
else {
$tampon .= $tmp;
if ( $flagNomGroupe == 1 ){
$flagNomGroupe = 2;
}
//debug('concat ', $tampon, $flagNomGroupe );
}
$this->position++;
}
return $resultat;
}
} |
Partager