如何仅从 .htaccess 文件中获取允许来自 xxx.xxx.xxx.xxx 的行

how to grab only the lines that have Allow from xxx.xxx.xxx.xxx in the .htaccess file

我正在尝试获取我的 .htaccess 文件中所有允许的地址。 目前我的 .htaccess 文件看起来像这样

Options +FollowSymlinks
RewriteEngine On
RewriteRule ^$ /admin [L]
Deny from all
Allow from 192.168.0.100
Allow from 127.0.0.1

我有这个代码

 $myfile = fopen("../.htaccess", "r") or die("Unable to open file!");
        $x =  fread($myfile,filesize("../.htaccess"));
        print_r(explode("\r\n",$x));
        fclose($myfile);

它读取完整的文件,输出是

Array ( [0] => Options +FollowSymlinks RewriteEngine On RewriteRule ^$ /admin [L] Deny from all Allow from 192.168.0.100 Allow from 127.0.0.1 #RewriteCond %{REMOTE_ADDR} ^127.0.0.1 #RewriteRule (.*) http://google.com [R=301,L] #RewriteCond %{REMOTE_ADDR} ^127.0.0.1 #RewriteRule index.php$ /admin [R=301,L] )

我想要的只是数组中来自 xxx.xxx.xxx.xxx 的 Allow。我想我需要某种正则表达式,但我对正则表达式不太敏锐

我想这会为你做:) 也是测试快速 Regex 表达式的好工具 - http://www.regexr.com/

$myfile = fopen("../.htaccess", "r") or die("Unable to open file!");
$x =  fread($myfile,filesize("../.htaccess"));
$pattern = '/(Allow .*)/';
preg_match($pattern, $subject, $matches);
print_r($matches);
fclose($myfile);

这应该可以满足您的要求:

preg_match_all( '|(?mi-Us)Allow From \d+\.\d+\.\d+\.\d+|', $x[0], $matches) ;

print_r($matches);

结果:

Array
(
    [0] => Array
        (
            [0] => Allow from 192.168.0.100
            [1] => Allow from 127.0.0.1
        )

)

不需要正则表达式:

$lines = array_filter(file('../.htaccess'), function($value) {
   return (stristr($value, 'allow from') !== FALSE);
});

$lines 将是:

Array
(
    [4] => Allow from 192.168.0.100
    [5] => Allow from 127.0.0.1
)

file() 会将每一行读入数组,array_filter() 使用 [=19 进行回调=]stristr()(不敏感字符串比较)会过滤掉不包含'allow from'的行。如果您需要数组从偏移量 0 开始,可以将 array_filter 包装在 array_values() 中以重新索引数组。

我也投票给 file()。这是使用简单的 foreach 循环的更简单的方法。

$result = array();
$fileArray = file('.htaccess');

foreach($fileArray as $n => $line)
{
    if(strpos($line, 'Allow from') !== false)
    {
        if(trim($line) !== "")
        {
            $result[$n] = trim($fileArray[$n]);
        }
    }
}

$result = array_values($result);
var_dump($result);