Advertisement
Guest User

Untitled

a guest
Aug 27th, 2013
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.20 KB | None | 0 0
  1. <?php
  2. $path = "C:/path/to/textfile"; // <- Do not use trailing slashes in path's
  3. $parts = array(
  4.   'HD ', 'BY ', 'WC ', 'PD ', 'SN ', 'SC ', 'PG ', 'LA ', 'CY ',
  5.   'LP ', 'TD ', 'CO ', 'IN ', 'NS ', 'RE ', 'IPC', 'PUB', 'AN '
  6. );
  7.  
  8. function extract_parts(array $parts, $str, $eol = PHP_EOL) {
  9.   $ret = array();
  10.   $current_record = array();
  11.   $current_keyword = null;
  12.   foreach (explode($eol, $str) as $line) {
  13.     $line=trim($line);
  14.     $substr = substr($line, 0, 3);
  15.     if ($substr == 'HD ') {
  16.       if (count($current_record)) $ret[] = $current_record;
  17.       $current_record = array_fill_keys($parts, '');
  18.     }
  19.     if (isset($current_record[$substr])) {
  20.       $current_keyword = $substr;
  21.       $line = trim(substr($line, 3));
  22.     }
  23.     if ($current_keyword) $current_record[$current_keyword] .= $line;
  24.   }
  25.   if (count($current_record)) $ret[] = $current_record;
  26.   return $ret;
  27. }
  28.  
  29. if ($handle = opendir($path)) { // Tip: using glob() would be more comfortable
  30.   while (false !== ($file = readdir($handle))) {
  31.     if ('.' === $file) continue;
  32.     if ('..' === $file) continue;
  33.     $ret = extract_parts($parts, file_get_contents($path . DIRECTORY_SEPARATOR . $file));
  34.   }
  35. }
  36.  
  37. var_dump($ret);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement