Glob is not working when directory name with speci

2019-02-19 13:45发布

问题:

I have issue while using glob function when path directory with square brackets.

// 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>';

Above code is working but when directory name with square brackets like dir[name] or dir - [name] then its not working.

// 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>';

回答1:

Thanks for all of you.

I got exact solution for my query. below code is a working for me

$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>';


回答2:

This is what I use:
$path = str_replace(['[',']',"\f[","\f]"], ["\f[","\f]",'[[]','[]]'], $path);

All in one line.



回答3:

[foo] has a special meaning, it represents a character class (regular expression syntax).

So to have [ and ] mean square brackets literally, you have to escape them – by preceding them with a backslash.



回答4:

Try

$path = 'temp'. DIRECTORY_SEPARATOR .'dir - [name]';
$from = array('[',']');
$to   = array('\[','\]');
$files =glob(str_replace($from,$to,$path . "\\*.txt"));
echo '<pre>';
    print_r($files);
echo '</pre>';


标签: php wordpress