Skip to content

Instantly share code, notes, and snippets.

@borisguery
Created September 25, 2012 15:28
Show Gist options
  • Save borisguery/3782594 to your computer and use it in GitHub Desktop.
Save borisguery/3782594 to your computer and use it in GitHub Desktop.
Split a directory into sub-directories
<?php
function directorySplit($dir, $segmentSize = 2, $maxSegment = 3, $dirSeparator = DIRECTORY_SEPARATOR)
{
$segmentedDir = '';
for ($i = 0, $segmentOffset = 0; $i < $maxSegment && strlen($dir) > $segmentOffset; ++$i, $segmentOffset = $segmentSize * $i) {
$segment = substr($dir, $segmentOffset, $segmentSize) . $dirSeparator;
if (strlen($segment) < $segmentSize) {
break;
}
$segmentedDir .= $segment;
}
$segmentedDir .= substr($dir, $maxSegment * $segmentSize);
return rtrim($segmentedDir, $dirSeparator);
}
// Tests
for ($i = 30; $i > 0; --$i) {
$dir = substr(sha1(uniqid()), 0, $i + 1);
printf("%s => %s (%s)\n", $dir, directorySplit($dir), ($dir === str_replace('/', '', directorySplit($dir))) ? 'true' : 'false');
}
// Results
/**
c82695e43e3f3230525745267049a68 => c8/26/95/e43e3f3230525745267049a68 (true)
87df80997a0317f1e6ab5b8f3fd3f0 => 87/df/80/997a0317f1e6ab5b8f3fd3f0 (true)
93d6c3454a646c8fe8b0379c0b918 => 93/d6/c3/454a646c8fe8b0379c0b918 (true)
6f6e23befde8bd254c10b2c39439 => 6f/6e/23/befde8bd254c10b2c39439 (true)
87a6eea60ca60c476341cb86522 => 87/a6/ee/a60ca60c476341cb86522 (true)
12f418fb116ae9dca3f4fb0605 => 12/f4/18/fb116ae9dca3f4fb0605 (true)
4bd58a8d37a1b9d49ed434033 => 4b/d5/8a/8d37a1b9d49ed434033 (true)
06990ba193aab494a4687409 => 06/99/0b/a193aab494a4687409 (true)
4373d2e733a132690e1edd1 => 43/73/d2/e733a132690e1edd1 (true)
e757c48741a814fa546904 => e7/57/c4/8741a814fa546904 (true)
3b20db2e085ddc60462cf => 3b/20/db/2e085ddc60462cf (true)
a2b8e84e12278745f0b0 => a2/b8/e8/4e12278745f0b0 (true)
5859ddc28ed82b0ec55 => 58/59/dd/c28ed82b0ec55 (true)
db64a21aa435b3c610 => db/64/a2/1aa435b3c610 (true)
0e8d235e182e74814 => 0e/8d/23/5e182e74814 (true)
21dc6a2a68f422fb => 21/dc/6a/2a68f422fb (true)
27a9eb35e0cf561 => 27/a9/eb/35e0cf561 (true)
d48984e2c38d23 => d4/89/84/e2c38d23 (true)
45f039bbc6f38 => 45/f0/39/bbc6f38 (true)
7c39c274945e => 7c/39/c2/74945e (true)
d96e2169da1 => d9/6e/21/69da1 (true)
06b40d7a3d => 06/b4/0d/7a3d (true)
1c9b34b1d => 1c/9b/34/b1d (true)
5aa817ad => 5a/a8/17/ad (true)
4a5fb48 => 4a/5f/b4/8 (true)
7e8262 => 7e/82/62 (true)
9b58f => 9b/58/f (true)
a548 => a5/48 (true)
3cb => 3c/b (true)
fd => fd (true)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment