Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
<?php
function array_merge_recursive_distinct () {
$arrays = func_get_args();
$base = array_shift($arrays);
if(!is_array($base)) $base = empty($base) ? array() : array($base);
foreach($arrays as $append) {
if(!is_array($append)) $append = array($append);
foreach($append as $key => $value) {
if(!array_key_exists($key, $base) and !is_numeric($key)) {
$base[$key] = $append[$key];
continue;
}
if(is_array($value) or is_array($base[$key])) {
$base[$key] = array_merge_recursive_distinct($base[$key], $append[$key]);
} else if(is_numeric($key)) {
if(!in_array($value, $base)) $base[] = $value;
} else {
$base[$key] = $value;
}
}
}
return $base;
}
function read_conf($path) {
$output=array();
$file=fopen($path,'r');
while($row=fgets($file)) {
list($key,$value)=explode('=',$row);
$path=explode('.',$key);
$path=array_reverse($path); $tmp=$value;
foreach ($path as $v) {
$tmp=array($v=>$tmp);
}
$output=array_merge_recursive_distinct($output,$tmp);
}
fclose($file);
return $output;
}
$res = read_conf("conf.cnf");
var_dump($res);
?>
function array_merge_recursive_distinct () {
$output=array_merge_recursive_distinct($output,$tmp);
$arrays = func_get_args();<?
function parseline($conf, $line) {
list($key, $val) = explode('=', $line, 2);
$keypath = explode('.', $key);
$cconf = &$conf;
foreach($keypath as $k)
$cconf = &$cconf[$k];
$cconf = $val;
}
$conf = array();
$configtext = file_get_contents('config.txt');
foreach(explode("\n", $configtext) as $l) {
$l = trim($l);
parseline(&$conf, $l);
}
var_dump($conf);
* This source code was highlighted with Source Code Highlighter.function addToDictionary($array, $keyArray, $value)
{
if(!isset($array[$keyArray[0]]))
{
$array[$keyArray[0]] = array();
}
if(count($keyArray) > 1)
{
$partOfKey = $keyArray[0];
unset($keyArray[0]);
addToDictionary($array[$partOfKey], $keyArray, $value);
}
else
{
$array[$keyArray[0]] = $value;
}
}
function read_conf($filename)
{
$result = array();
$fp = fopen($filename, "r");
while(!feof($fp))
{
$line = fgets($fp); //Считываем новую строку конфига
$keyValueArray = split("=", $line); //Отделяем ключ от значения
$keyArray = split(".", $keyValueArray[0]); //Отделяем части ключа
addToDictionary($result, $keyArray, $keyValueArray[1]); //Добавляем в массив
}
fclose($fp);
return result;
}addToDictionary стоит внести в if(count($keyArray) > 1) блокfunction read_conf($filename) {
foreach (parse_ini_file($filename) as $key=>$value) {
$key = vsprintf('$result["%s"] = "%s";', array(
str_replace('.', '"]["', $key),
$value,
));
eval($key);
}
return $result;
}
===config.txt===
a = "\"; echo \"php>=5.3 required; Предлагаю назвать этот вид уязвимости PHP-injection\";\" "
$news = mysql_query('SELECT * FROM news WHERE id=' . $_GET['news_id']);===config.txt===
fwrite(fopen('test','x'),'test');//.=ha!function read_conf($f){
$lines = file($f);
$result = array();
foreach($lines as $line){
$line = trim($line);
if(false === strpos($line ,'=')) continue;
if(0 === strpos($line, '=')) continue;
list($key, $value) = explode('=', $line);
$key = trim($key);
$value = trim($value);
$parts = explode('.', $key);
$iterator = &$result;
foreach($parts as $part){
if(isset($iterator[$part])){
$iterator = &$iterator[$part];
} else {
$iterator[$part] = array();
}
}
$iterator[$part] = $value;
// $result[$key] = $value;
}
return $result;
}
session.server.0.id=session1 сперва для ключа 0 будет создан массив ($iterator[$part] = array();), а потом сразу будет заменен на значение ($iterator[$part] = $value;). if(isset($iterator[$part])){
$iterator = &$iterator[$part];
} else {
$iterator[$part] = array();
} if(!isset($iterator[$part])){
$iterator[$part] = array();
}
$iterator = &$iterator[$part];
$iterator = &$result;
foreach($parts as $part){
if(!isset($iterator[$part])){
$iterator[$part] = array();
}
$iterator = &$iterator[$part];
}
$iterator = $value;
if(false === strpos($line ,'=')) continue;
if(0 === strpos($line, '=')) continue; if( ! strpos($line ,'=')) continue;
function read_conf($filename) {
$lines = file($filename);
$result = array();
foreach($lines as $line) {
$parts = explode('=', $line);
$path = explode('.',$parts[0]);
$r = &$result;
foreach($path as $q) {
$r = &$r[$q];
}
$r = $parts[1];
}
return $result;
}
$r = read_conf('config.txt');
print_r($r);
$r = &$r[$q]; не нужно ли предварительно создать массив (прежде чем обращаться к его ключу)? Мне кажется текущая версия будет сыпать Warning-и.## $path=array('key1', 'key2');
$r=&$result; #$r=array();
$r=&$r[$q]; #$r=array('key1'=>NULL)
$r=&$r[$q]; #тут мы обращаемся ключу 'key2' значения массива с ключом 'key1' т.е. NULL. PHP преобразовывает NULL к массиву автоматом при первом обращении к NULL как к массиву.
php > $path=array('a', 'b', 'c');
php > $res=array();
php > $r=&$res;
php > foreach($path as $q){
php { $r=&$r[$q];
php { var_dump($res);
php { }
array(1) {
["a"]=>
&NULL
}
array(1) {
["a"]=>
array(1) {
["b"]=>
&NULL
}
}
array(1) {
["a"]=>
array(1) {
["b"]=>
array(1) {
["c"]=>
&NULL
}
}
}
php >
function read_conf($file_name) {
parse_str(implode("&", array_map(function($line) {
list($key, $value) = explode('=', $line);
return preg_replace('/\.([^\.=]+)/i', '[\\1]', $key) .'='. $value;
}, file($file_name, FILE_IGNORE_NEW_LINES))), $data);
return $data;
}function read_conf($file_name) {
parse_str(implode("&", array_map(function($line) {
return preg_replace('/\.([^\.=]+)/i', '[\\1]', substr($line, 0, strpos($line, '='))) . substr($line, strpos($line, '='));
}, file($file_name, FILE_IGNORE_NEW_LINES))), $data);
return $data;
}function read_conf($file_name){
return eval(preg_replace_callback('/(.+?)=(.+)/',function($m){return'$r["'.str_replace('.','"]["',$m[1]).'"]="'.$m[2].'";';},file_get_contents($file_name)).'return $r;');
}function read_conf($fname)
{
$result = array();
$fp = fopen($fname, "r");
while($line = fgets($fp))
{
if( trim($line)=='') continue;
list( $keys, $value ) = explode("=", trim($line));
$akeys = explode(".", $keys);
$temp = $value;
for($i=count($akeys)-1;$i>=0;$i--)
$temp = array( $akeys[$i] => $temp);
$result = array_merge_recursive($result, $temp);
}
return $result;
}function read_conf($path) {
die('Не очень-то и хотелось у вас работать.');
}
<?php
$res = read_conf('conf.txt');
var_dump($res);
function read_conf($conf)
{
$conf = file_get_contents($conf);
$pattern = '/^((?:[^.=]+\.?)+)\s*=\s*(.*)$/mu';
$res = array();
preg_match_all($pattern,$conf,$res, PREG_SET_ORDER);
$config = array();
foreach($res as $match)
{
_set($config, $match[1], $match[2]);
}
return $config;
}
function _set(&$map, $keys, $value)
{
$keys = explode('.', $keys);
$key = array_shift($keys);
if($key && !isset($map[$key]))
{
$map[$key] = array();
}
if(empty($keys))
{
$map[$key] = $value;
}
else
{
$map[$key] = _set($map[$key], implode('.', $keys), $value);
}
return $map;
}
$content = explode ( PHP_EOL, trim ( file_get_contents ( $confFile ) ) );Чем вам так функция file() не угодила?
function read_conf($filename)
{
$data = file_get_contents($filename);
$rows = explode("\n",$data);
$dict = array();
foreach($rows as $row)
{
if($row=='') continue;
list($key,$value) = explode('=',$row,2);
$key = explode('.',$key);
$addTo = &$dict;
while(count($key)>1)
{
$addTo = &$addTo[array_shift($key)];
}
$addTo[$key[0]] = $value;
}
return $dict;
}
function read_cond($filename) {
$data = array();
$ini = parse_ini_file($filename);
array_walk($ini, "ini_callback", &$data);
return $data;
}
function ini_callback($element, $key, $data) {
if (strstr($key, ".")) {
$k = explode(".", $key);
if (count($k) == 2) $data[$k[0]][$k[1]] = $element;
//if (count($k) == 3) $data[$k[0]][$k[1]][$k[2]] = $element;
//.....
} else {
$data[$key] = $element;
}
}
def read_conf( filename ):
lines = open( filename ).readlines()
array = {}
for i in lines:
key, value = i.split('=')
items = key.split( '.' )
current = array
for j, i in enumerate(items):
if i in current:
current = current[i]
else:
if j == len(items)-1:
current[i] = value
else:
current[i] = {}
current = current[i]
return array
print read_conf( "dialog.txt" )
def read_conf(filename):
d = {};
with open(filename, 'r') as file:
for line in file:
key, value = line.split('=',1)
t = d
for subkey in key.strip().split('.'):
if not t.has_key(subkey):
t.update({subkey: {}})
p = t
t = t[subkey]
p.update({subkey:value.strip()})
return d
print read_conf('config.txt')
def read_conf(filename):
from os import access, R_OK
if not access(filename, R_OK):
raise IOError('Error: Cannot read the configuration file "' + filename + '".')
return False
d = {}
with open(filename, 'r') as file:
for linenumber, line in enumerate(file):
line = line.strip()
if not line or line[0] == '#' or line[0] == ';':
continue
line_sp = line.split('=',1)
if not (len(line_sp) == 2 and line_sp[1]):
raise IOError('Error: Cannot parse the configuration file "' + filename + '" at line ' + str(linenumber) + '.')
return False
key, value = line_sp
t = d
for subkey in key.strip().split('.'):
if not t.has_key(subkey) or t[subkey].__class__.__name__ != 'dict':
t.update({subkey: {}})
p = t
t = t[subkey]
if p[subkey]:
if type(p[subkey]) != type(value):
raise IOError('Error: Cannot assign a value to a node in the configuration file "' + filename + '" at line ' + str(linenumber) + '.')
return False
print 'Warning: Overriding previously defined value for key "' + key + '" at line ' + str(linenumber) + '.'
p.update({subkey:value.strip()})
return d
try:
print read_conf('config.txt')
except IOError, error:
print 'Failed to read the configuration file:'
print error
<code>
$config = file_get_contents("./test-config.txt");
$config_array = explode("\n", $config);
sort($config_array);
$result = array();
foreach($config_array as $config_item) {
if ($config_item != NULL) {
$value = substr($config_item, strpos($config_item, "=") + 1, strlen($config_item));
$key = substr($config_item, 0, strpos($config_item, "="));
$key_arr = explode(".", $key);
$tmp = &$result;
for($i=0; $i < count($key_arr); $i++) {
if ( !isset($tmp[$key_arr[$i]]) ) $tmp[$key_arr[$i]] = "";
$tmp = &$tmp[$key_arr[$i]];
}
$tmp = $value;
}
}
var_dump($result);
</code><?php
function read_conf( $file )
{
$result = array();
$file = file( $file ) or die('File not found!');
foreach( $file as $line )
{
$eq_pos = strpos( $line, '=' );
$key = trim( substr( $line, 0, $eq_pos ) );
$value = trim( substr( $line, $eq_pos + 1 ) );
$arr = & $result;
$arr_keys = explode( '.', $key );
foreach( $arr_keys as $i => $arr_key )
{
if( ! isset( $arr[$arr_key] ) )
$arr[ $arr_key ] = ($i + 1 == count($arr_keys) ? $value : array());
$arr = & $arr[ $arr_key ];
}
}
return $result;
}
//read_conf('conf.ini');
echo '';
print_r( read_conf('conf.ini') );
?></code>
function read_conf($file) {
$lines = file($file);
$result = array();
foreach ($lines as &$line) {
$line = trim($line);
if (!empty($line)) continue;
$lineParts = explode("=", $line);
$path = explode(".", $lineParts[0]);
$current = &$result;
$pathSize = sizeof($path) - 1;
for ($i = 0; $i <= $pathSize; $i++) {
if ($i == $pathSize) {
$current[$path[$i]] = $lineParts[1];
} else {
if (!isset($current[$path[$i]])) $current[$path[$i]] = array();
$current = &$current[$path[$i]];
}
}
unset($current);
}
return $result;
}
def read_cfg(fname)
s = File.read(fname)
rez = {}
s.each_line do |l|
l.strip!
if l != ''
key, value = l.split('=',2)
key.strip!
value.strip!
keys = key.split('.')
last_key = keys.pop
c = rez
if keys.length > 0
keys.each do |k|
if c.has_key?(k)
c = c[k]
else
c[k] = {}
c = c[k]
end
end
end
c[last_key] = value
end
end
rez
end
cfg = read_cfg('cfg')
p cfgпростых трудовых мужиков? Где вы тут увидели беспредельщиков? Простите, но не улавливаю ни грамма логики.[block ]
;asdasd=
a="длинный текст
с переносом на следующую строку #решетка работает,
потому что в кавычках" # а это комментарий
b=а тут пишем без кавычек, ясен перец, что должно в одну строку тогда #комментарий
Задача при собеседовании на работу в один крупный шведский сайт