如何使用插入符号(';^';)在PCRE-Regex语法中仅排除一次文件/文件夹


How do you use caret ('^') to exclude files/folders only once in PCRE Regex syntax?

例如,我在conf.php文件中有:

$GLOBALS["no_access"] = '^forbidden|restricted|xampp|apache'_pb';

阻止查看这些文件/文件夹,并希望限制这些字符串(文件夹/文件)的次数。这是因为这是一个intranet项目,可能有一个我不想访问的文件夹与我想使用的文件或文件夹同名。此外,是否可以选择第一个实例,但不能稍后选择?

这是为了更改Joomla的一个组件,称为eXtplorer,一个文件管理器。

无论哪种方式都可以,但白名单将是安全的,而不是黑名单(因此您只能访问以x开头的目录)。

您想要的是一个正则表达式,可以用来检查字符串的开头是否以与文件夹匹配的特定模式开头。

$regex = '/^(?:forbidden|restricted|xampp|apache_pb)/i';

在php中,它可能看起来像这样:

function startIsRestricted($string) {
    return preg_match('/^(?:forbidden|restricted|xampp|apache_pb)/i', $string);
}

编辑

阅读该讨论,听起来更像是你想限制对文件夹的访问。在这种情况下,你可能想看看用htaccess和htpasswd保护目录的文档,你可以在apache网站或这个网站上找到,对整个目录进行更多的

在PHP中进行限制是不安全的。。。

编辑2

代码经过排序测试;至少我现在在数组映射(duh)上做了一个内爆,并修复了明显的拼写错误。

但它至少应该给出一个很好的想法,说明如何递归地对字符串中的每个目录进行检查。。。

/**
 * Function to check an entire string recursively to see if dissalowed directories are present
 * Assuming the string seperator will be a forwardslash
 *
 * @param string $string String to be evaluated against the dissalowed directory list given or else default
 * @param array $dissallow array of strings which are forbidden to be at the start of any of the directories
 * @param string $sep The seperator for the directory levels
 * 
 * @return string
 */
function test_directory ($string, array $dissallow = array('forbidden', 'restricted', 'xampp', 'apache_pb'), $sep = '/') {
    $regex  = '/^(?:' . implode('|', array_map ('preg_quote', $dissallow)) . ')/i';
    $dirs   = explode($sep, $string);
    foreach($dirs as $dir) {
        // true will mean a match is found and thus present in the beginning of a directory in $string
        if(preg_match($regex, $dir))
            return true;
    }
    return false;
}

现在我应该注意到,在这种情况下,正则表达式可能会减慢速度,而且应该使用得太多,如果与dissalow数组中的任何字符串直接匹配都可以的话,那么应该根据$dissallow的每个条目检查$dirs中的每个$dir

对于PCRE,^表示匹配字符串的开头。对于|运算符,您说的是"thisORthat"。

使用您声明的正则表达式,您将无法满足您的期望。

/^(forbidden|restricted|xampp|apache'_pb)/i

将在一行(如目录列表)的开头匹配