我正在尝试获取.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。我想我需要某种正则表达式,但对正则表达式不太敏锐
答案 0 :(得分:2)
这应该按照您的要求进行:
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
)
)
答案 1 :(得分:2)
不需要正则表达式:
$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()会使用 stristr()(不敏感字符串比较)将每一行读入数组 array_filter()并进行回调将过滤掉不允许来自&#39;的行。如果需要从偏移量0开始数组,可以在 array_values()中包装array_filter以重新索引数组。
答案 2 :(得分:1)
我也投票给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);
答案 3 :(得分:0)
我想这会为你做:) 也是测试快速正则表达式的一个很好的工具 - 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);