Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $path = "C:/path/to/textfile"; // <- Do not use trailing slashes in path's
- $parts = array(
- 'HD ', 'BY ', 'WC ', 'PD ', 'SN ', 'SC ', 'PG ', 'LA ', 'CY ',
- 'LP ', 'TD ', 'CO ', 'IN ', 'NS ', 'RE ', 'IPC', 'PUB', 'AN '
- );
- function extract_parts(array $parts, $str, $eol = PHP_EOL) {
- $ret = array();
- $current_record = array();
- $current_keyword = null;
- foreach (explode($eol, $str) as $line) {
- $line=trim($line);
- $substr = substr($line, 0, 3);
- if ($substr == 'HD ') {
- if (count($current_record)) $ret[] = $current_record;
- $current_record = array_fill_keys($parts, '');
- }
- if (isset($current_record[$substr])) {
- $current_keyword = $substr;
- $line = trim(substr($line, 3));
- }
- if ($current_keyword) $current_record[$current_keyword] .= $line;
- }
- if (count($current_record)) $ret[] = $current_record;
- return $ret;
- }
- if ($handle = opendir($path)) { // Tip: using glob() would be more comfortable
- while (false !== ($file = readdir($handle))) {
- if ('.' === $file) continue;
- if ('..' === $file) continue;
- $ret = extract_parts($parts, file_get_contents($path . DIRECTORY_SEPARATOR . $file));
- }
- }
- var_dump($ret);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement