只是为了好玩,我写了这段代码。
ini_set('error_reporting', -1);
ini_set('display_errors', 1);
/**
* Recognising level of current header and header itself by counting prefixes
* before header
* @param string $string
* @param string $prefix
* @param &int $level
* @param &string $header
*/
function myGetLevelAndHeader($string, $prefix, &$level, &$header)
{
preg_match('/^((?:' . preg_quote($prefix) . ')*)(.*)$/', $string, $match);
$header = $match[2];
$level = strlen($match[1]) / strlen($prefix);
}
/**
* Adding to headers array to the desired dimension without recursion
* @param &array $headers ere
* @param integer $level
* @param string $header
*/
function myAddToHeaders(array &$headers, $level, $header)
{
$array = &$headers;
while ($level--)
{
//adding new dimension
is_null($array) ? $array = array() : end($array);
$last_key = key($array);
if (!is_null($last_key) && is_array($array[$last_key]))
$array = &$array[$last_key]; // going deeper
else
$array = &$array[]; // create new element and going deeper
};
$array[] = $header;
}
/**
* Simple parsing function
* @param array $lines
* @param string $prefix
* @return array
*/
function myParse(array $lines, $prefix = ' ')
{
$headers = array();
foreach ($lines as $line)
{
myGetLevelAndHeader($line, $prefix, $level, $header);
myAddToHeaders($headers, $level, $header);
}
return $headers;
}
$lines = file('file.txt');
print_r(myParse($lines, ' '));