Skip to content
Advertisement

How to select all js files which is located in a folder or under a subfolder

I want to import my script files dynamicly. I’ve coded a simple think but it is not working how I expected. I want to select all js files which is located in a folder and its subfolders.

    <script src="front/js/assets/jquery-3.6.0.min.js"></script>
    <?php
        foreach (glob( 'front/js/**/*.js') as $jsFile):
            $exception = [
                'front/js/assets/jquery-3.6.0.min.js',
                'front/js/main.js'
            ];
            if(!in_array($jsFile, $exception))
            echo '<script src="'.$jsFile.'"></script>'. PHP_EOL. "t";
        endforeach;
    ?>
    <script src="front/js/main.js"></script>

In this code, example.js is not loaded.

my folder

Advertisement

Answer

You can adjust your pattern this way. Note that the GLOB_BRACE flag allows you to replace {a, b, c} with ‘a’, ‘b’ or ‘c’

glob('{front/js/*.js,front/js/**/*.js}', GLOB_BRACE)

NB: Also The GLOB_BRACE flag is not available on some non-GNU systems, such as Solaris.

For more information, you can follow this link glob — Find pathnames matching a pattern

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement