Glob is not working when directory name with special characters like square brackets “[ ]”

前端 未结 4 1380
长发绾君心
长发绾君心 2021-01-13 01:47

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

// Example 1 - working
$path = \'temp\'. DIRECTORY_SEPARATOR .\'dir - name\'         


        
相关标签:
4条回答
  • 2021-01-13 02:01

    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>';
    
    0 讨论(0)
  • 2021-01-13 02:13

    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>';
    
    0 讨论(0)
  • 2021-01-13 02:22

    [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.

    0 讨论(0)
  • 2021-01-13 02:23

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

    All in one line.

    0 讨论(0)
提交回复
热议问题