当目录名称包含方括号“[]”等特殊字符时,Glob 不起作用

Kir*_*mar 5 php wordpress

当路径目录带有方括号时,我在使用 glob 函数时遇到问题。

// Example 1 - working
$path = 'temp'. DIRECTORY_SEPARATOR .'dir - name';
$files = glob($path . DIRECTORY_SEPARATOR . '*.txt');
// List all files 
echo '<pre>';
    print_r($files);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

上面的代码可以正常工作,但是当目录名称带有方括号(如 dir[name] 或 dir - [name])时,它就不起作用了。

// Example 2 - not working
$path = 'temp'. DIRECTORY_SEPARATOR .'dir - [name]';
$files = glob($path . DIRECTORY_SEPARATOR . '*.txt');
// result got empty if file on that directory 
echo '<pre>';
    print_r($files);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

Kir*_*mar 6

谢谢大家。

我的查询得到了确切的解决方案。下面的代码对我有用

$path = 'temp'. DIRECTORY_SEPARATOR .'dir - [name]';
$path = str_replace('[', '\[', $path);
$path = str_replace(']', '\]', $path);
$path = str_replace('\[', '[[]', $path);
$path = str_replace('\]', '[]]', $path);
$files = glob($path . DIRECTORY_SEPARATOR . '*.txt');
// List files
echo '<pre>';
    print_r($files);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)