PHP Regex for matching a UNC path

前端 未结 2 825
我寻月下人不归
我寻月下人不归 2020-12-18 12:55

I\'m after a bit of regex to be used in PHP to validate a UNC path passed through a form. It should be of the format:

\\\\server\\something

2条回答
  •  抹茶落季
    2020-12-18 13:29

    Echo your regex as well, so you see what's the actual pattern, writing those slashes inside PHP can become akward for the pattern, so you can verify it's correct.

    Also you should put ^ at the beginning of the pattern to match from string start and $ to the end to specify that the whole string has to be matched.

    \\server\something
    

    Regex:

     ~^\\\\server\\something$~
    

    PHP String:

    $pattern = '~^\\\\\\\\server\\\\something$~';
    

    For the repetition, you want to say that a server exists and it's followed by one or more \something parts. If server is like something, this can be simplified:

    ^\\(?:\\[a-z]+){2,}$
    

    PHP String:

    $pattern = '~^\\\\(?:\\\\[a-z]+){2,}$~';
    

    As there was some confusion about how \ characters should be written inside single quoted strings:

    # Output:
    #
    # * Definition as '\\' ....... results in string(1) "\"
    # * Definition as '\\\\' ..... results in string(2) "\\"
    # * Definition as '\\\\\\' ... results in string(3) "\\\"
    
    $slashes = array(
        '\\',
        '\\\\',
        '\\\\\\',
    );
    
    foreach($slashes as $i => $slashed) {
        $definition = sprintf('%s ', var_export($slashed, 1));
        ob_start();
        var_dump($slashed);
        $result = rtrim(ob_get_clean());    
        printf(" * Definition as %'.-12s results in %s\n", $definition, $result);
    }
    

提交回复
热议问题