Génération récursive d'une arborescence de répertoires

Contenu du snippet

<?php
/**********************************************************
* Name      : setDirTree()
* Aim      : recursie function which generates a directories 
*           tree
*
* Params : string $_dirTree
* Return : void
* Author : Hugo 'Emacs' HAMON
* Web    : http://www.hugohamon.com
**********************************************************/
function setDirTree($_dirTree) {
    // Is parameter null or empty ?
    if(!empty($_dirTree) && is_string($_dirTree)) {
   
        // Check if the root directory exists in the string
        if(preg_match('`^\.\/[^\.\.\/]`si', $_dirTree)) {
            // Go to the root directory
            chdir('.');
            // Delete the root element
            $_dirTree = str_replace('./','',$_dirTree);
        }
        
        // Check if symbolic links exist in the string
        if(preg_match('`^(\.\/)?[\.\.\/]{1,}`si', $_dirTree, $matches)) {
        
            chdir($matches[0]);
            $_dirTree = str_replace($matches[0],'',$_dirTree);
        }
        // Explode the string as an array
        $path = explode('/', $_dirTree);
        // Check if the directory exists
        if(!is_dir($path[0])) {
            // Create directory
            mkdir($path[0]);
        }
        // Move inside it
        chdir($path[0]);
        // Delete the first array entry
        array_shift($path);
        // Implode the array as a string
        $path = implode('/', $path);
        // Recursive call
        setDirTree($path);
    }
}
?>


Compatibilité : PHP 3, PHP 4, PHP 5

Disponible dans d'autres langages :

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.