class bencoded {
var $data = array();
var $buffer = '';
var $sp = 0;
function getchar() {
if($this->sp == strlen($this->buffer))
return false;
$ch = $this->buffer[$this->sp];
$this->sp++;
return $ch;
}
function getword() {
switch($ch = $this->getchar()) {
case false:
return false;
case 'i':
return $this->integers(); //整数
case 'l':
return $this->lists(); //列表
case 'd':
return $this->dictionaries(); //字典
default:
return $this->strings($ch); //字符串
}
}
function decode($in) {
$this->buffer = $in;
$sp = 0;
while(($t = $this->getword()) !== false)
$this->data[] = $t;
print_r($this->data);
}
function integers() {
$t = '';
while(($ch = $this->getchar()) != 'e')
$t .= $ch;
return array('type' => 'integers', 'value' => $t);
}
function strings($n=0) {
while(($ch = $this->getchar()) != ':')
$n .= $ch;
$t = '';
for($i=0;$i<$n;$i++)
$t .= $this->getchar();
return array('type' => 'strings', 'value' => $t);
}
function lists() {
$t = array('type' => 'lists');
while($this->buffer[$this->sp] != 'e')
$t[] = $this->getword();
$this->getchar();
return $t;
}
function dictionaries() {
$t = array('type' => 'dictionaries');
while($this->buffer[$this->sp] != 'e')
$t[] = array('key' => $this->strings(), 'value' => $this->getword());
$this->getchar();
return $t;
}
}$o = new bencoded;
$bt = 'd4:path3:C:\8:filename8:test.txte';
$o->decode($bt);注:省略了编码方法
var $data = array();
var $buffer = '';
var $sp = 0;
function getchar() {
if($this->sp == strlen($this->buffer))
return false;
$ch = $this->buffer[$this->sp];
$this->sp++;
return $ch;
}
function getword() {
switch($ch = $this->getchar()) {
case false:
return false;
case 'i':
return $this->integers(); //整数
case 'l':
return $this->lists(); //列表
case 'd':
return $this->dictionaries(); //字典
default:
return $this->strings($ch); //字符串
}
}
function decode($in) {
$this->buffer = $in;
$sp = 0;
while(($t = $this->getword()) !== false)
$this->data[] = $t;
print_r($this->data);
}
function integers() {
$t = '';
while(($ch = $this->getchar()) != 'e')
$t .= $ch;
return array('type' => 'integers', 'value' => $t);
}
function strings($n=0) {
while(($ch = $this->getchar()) != ':')
$n .= $ch;
$t = '';
for($i=0;$i<$n;$i++)
$t .= $this->getchar();
return array('type' => 'strings', 'value' => $t);
}
function lists() {
$t = array('type' => 'lists');
while($this->buffer[$this->sp] != 'e')
$t[] = $this->getword();
$this->getchar();
return $t;
}
function dictionaries() {
$t = array('type' => 'dictionaries');
while($this->buffer[$this->sp] != 'e')
$t[] = array('key' => $this->strings(), 'value' => $this->getword());
$this->getchar();
return $t;
}
}$o = new bencoded;
$bt = 'd4:path3:C:\8:filename8:test.txte';
$o->decode($bt);注:省略了编码方法
(
[0] => Array
(
[type] => dictionaries
[0] => Array
(
[key] => Array
(
[type] => strings
[value] => path
) [value] => Array
(
[type] => strings
[value] => C:\
) ) [1] => Array
(
[key] => Array
(
[type] => strings
[value] => filename
) [value] => Array
(
[type] => strings
[value] => test.txt
) ) ))