update page now
Laravel Live Japan

Voting

: five plus one?
(Example: nine)

The Note You're Voting On

Anonymous
13 years ago
Here is a function that decreases the numbers inside a string (useful to convert DOM object into simplexml object)

e.g.: decremente_chaine("somenode->anode[2]->achildnode[3]") will return "somenode->anode[1]->achildnode[2]"

the numbering of the nodes in simplexml starts from zero, but from 1 in DOM xpath objects

<?php
function decremente_chaine($chaine)
    {
        //récupérer toutes les occurrences de nombres et leurs indices
        preg_match_all("/[0-9]+/",$chaine,$out,PREG_OFFSET_CAPTURE);
            //parcourir les occurrences 
            for($i=0;$i<sizeof($out[0]);$i++)
            {
                $longueurnombre = strlen((string)$out[0][$i][0]);
                $taillechaine = strlen($chaine);
                // découper la chaine en 3 morceaux
                $debut = substr($chaine,0,$out[0][$i][1]);
                $milieu = ($out[0][$i][0])-1;
                $fin = substr($chaine,$out[0][$i][1]+$longueurnombre,$taillechaine);
                 // si c'est 10,100,1000 etc. on décale tout de 1 car le résultat comporte un chiffre de moins
                 if(preg_match('#[1][0]+$#', $out[0][$i][0]))
                 {
                    for($j = $i+1;$j<sizeof($out[0]);$j++)
                    {
                        $out[0][$j][1] = $out[0][$j][1] -1;
                    }
                 }
                $chaine = $debut.$milieu.$fin;
            }
        return $chaine;
    }
?>

<< Back to user notes page

To Top