Skip to content

Instantly share code, notes, and snippets.

@brucefoster
Created January 17, 2015 20:20
Show Gist options
  • Save brucefoster/f02d3fc26d89c013cd6a to your computer and use it in GitHub Desktop.
Save brucefoster/f02d3fc26d89c013cd6a to your computer and use it in GitHub Desktop.
Multiple file merger (PHP)
<?php
class Merger {
private static $mergePending = array();
private static $mergeStats = array();
/* public static function mergeFiles
* @var mixed $filesArray array of names of files (including directories) to merge from
* @var string $destinationFile name of file to save merged files to
* @var mixed $splitterFunction anonymous function providing splitting of each file, in: string, out: array of items
* @var mixed $joinerFunction anonymous function providing merging all files with delimiter, in: array of items, out: string
* @return mixed stats for current merge operation
*/
public static function mergeFiles( $filesArray, $destinationFile, $splitterFunction, $joinerFunction ) {
foreach ( $filesArray as $ID => $file ) {
$fileContents = file_get_contents( $file );
$nesessaryParts = $splitterFunction( $fileContents );
$newPartCounter = 0;
foreach ( $nesessaryParts as $part ) {
if( !in_array( $part, self::$mergePending ) ) {
self::$mergePending[] = $part;
$newPartCounter ++;
}
}
self::$mergeStats[] = "Added $newPartCounter parts for merging from $file";
}
self::$mergeStats[] = "Total parts count is " . count( self::$mergePending );
$destinationFileContents = $joinerFunction( self::$mergePending );
$fileWrite = fopen( $destinationFile, 'w+' );
fwrite( $fileWrite, $destinationFileContents );
return self::$mergeStats;
}
}
// Example
$details = Merger::mergeFiles(
array( '01.html', '02.html', '03.html' ),
'_test.spf',
function( $file ) {
$replaces = array();
for( $count = 1; $count <= 9; $count ++ ) {
$replaces[ "value=$count" ] = '';
}
return explode( "<hr/>", strtr( $file, $replaces ) );
},
function( $array ) { return implode( $array, "<hr/>" ); }
);
var_dump( $details );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment