in PHP 7.4, given a folder structure of web/dist/assets, where the assets folder has…
- User
in PHP 7.4, given a folder structure of web/dist/assets, where the assets folder has multiple files following the naming scheme of
-.js, I need a script that does the following:- Takes in an array of bundleNames, i.e. ['main', 'secondary', ... ]
- Looks at the assets folder
- Finds the .js files with bundleNames matching the names from the input array
- Returns the full names of those files (including the )
- Assistant
Here is a PHP script that should achieve the described functionality:
php<?php // Define the input array of bundleNames $bundleNames = ['main', 'secondary']; // Define the path to the assets folder $assetsPath = 'web/dist/assets'; // Get a list of all .js files in the assets folder $jsFiles = glob($assetsPath . '/*.js'); // Iterate over the .js files and look for matches with the input bundleNames $matchingFiles = []; foreach ($jsFiles as $jsFile) { // Get the filename without the directory path or the file extension $filename = basename($jsFile, '.js'); // Split the filename into bundleName and hash using the "-" delimiter $parts = explode('-', $filename); // Check if the bundleName matches any of the input bundleNames if (in_array($parts[0], $bundleNames)) { $matchingFiles[] = $filename . '.js'; } } // Print out the full names of the matching files foreach ($matchingFiles as $matchingFile) { echo $matchingFile . "\n"; } - User
okay do that but only add the part of the filename after assets/, don't include the entire directory structure
- Assistant
Sure, here's the modified script that only returns the part of the filename after
assets/:php<?php // Define the input array of bundleNames $bundleNames = ['main', 'secondary']; // Define the path to the assets folder $assetsPath = 'web/dist/assets'; // Get a list of all .js files in the assets folder $jsFiles = glob($assetsPath . '/*.js'); // Iterate over the .js files and look for matches with the input bundleNames $matchingFiles = []; foreach ($jsFiles as $jsFile) { // Get the filename without the directory path or the file extension $filename = basename($jsFile, '.js'); // Split the filename into bundleName and hash using the "-" delimiter $parts = explode('-', $filename); // Check if the bundleName matches any of the input bundleNames if (in_array($parts[0], $bundleNames)) { // Add only the part of the filename after "assets/" $matchingFiles[] = substr($jsFile, strpos($jsFile, 'assets/') + 7); } } // Print out the names of the matching files foreach ($matchingFiles as $matchingFile) { echo $matchingFile . "\n"; }