Skip to content

Instantly share code, notes, and snippets.

@aziraphale
Last active January 11, 2016 16:14
Show Gist options
  • Save aziraphale/edf8a1b1ad049f4e08ee to your computer and use it in GitHub Desktop.
Save aziraphale/edf8a1b1ad049f4e08ee to your computer and use it in GitHub Desktop.
Windows' cmd.exe doesn't expand filename globs passed to PHP (and others). This function expands glob strings in PHP's $argv array.
<?php
/**
* Fixes PHP's $argv array (or, rather, a list of filenames that is assumed to
* come from $argv) to expand glob strings on Windows, where the cmd.exe shell
* doesn't expand globs before passing arguments to called commands/programs.
*
* @link https://gist.github.com/aziraphale/edf8a1b1ad049f4e08ee
* @param array $argv
* @return array
*/
function windowsFixGlobArgv(array $argv)
{
// Intentionally avoid overwriting the passed array just in case we want
// to leave it untouched for other purposes
$out = [];
foreach ($argv as $v) {
if (($v[0] !== "'" && substr($v, -1) !== "'") && strlen($v) !== strcspn($v, '*?{}[]')) {
// String contains glob-style metacharacters and isn't single-quoted
$matches = glob($v, GLOB_NOSORT | GLOB_NOCHECK | GLOB_BRACE);
if ($matches && is_array($matches)) {
foreach ($matches as $match) {
$out[] = $match;
}
continue;
}
}
$out[] = $v;
}
return $out;
}
// Use it something like this:
$files = array_slice($argv, 1);
if (stripos(PHP_OS, 'WIN') !== false) {
$files = windowsFixGlobArgv($files);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment