Skip to content

Instantly share code, notes, and snippets.

@collei
Last active June 2, 2023 17:15
Show Gist options
  • Save collei/e16b8e277c150ce3eef8ba97fd235a8b to your computer and use it in GitHub Desktop.
Save collei/e16b8e277c150ce3eef8ba97fd235a8b to your computer and use it in GitHub Desktop.
Provides a simple manner to obtain a final portion of a file path with an optional desired number of folder levels.
/**
* Provides a simple manner to obtain a final portion of a file path
* with the desired number of parent folders, if any.
*
* @param string $path
* @param int $withFolderLevels = 0
* @param string|null $withSeparator = null
* @return string
*/
function filename_from_path($path, $withFolderLevels = 0, $withSeparator = null)
{
if (strrpos($path, '/') !== false) {
$separator = '/';
} elseif (strrpos($path, '\\') !== false) {
$separator = '\\';
} else {
return '';
}
//
$path = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $path);
//
if ($withFolderLevels > 0) {
$levels = explode(DIRECTORY_SEPARATOR, $path);
$included = [];
$nth = count($levels) - 1;
for ($n = $nth - $withFolderLevels; $n <= $nth; ++$n) {
$included[] = $levels[$n];
}
return implode($withSeparator ?? $separator, $included);
}
//
$p = strrpos($path, DIRECTORY_SEPARATOR);
//
return substr($path,1+$p);
}
////// testing /////////////////////////////
$filepath = 'c:\your\apache\folder\www\myWebApp\storage\files\invoices\543287423987542357237538823.pdf';
$alpha = getFileName($filepath); // 543287423987542357237538823.pdf
$bravo = getFileName($filepath, 1); // invoices\543287423987542357237538823.pdf
$charlie = getFileName($filepath, 2); // files\invoices\543287423987542357237538823.pdf
$delta = getFileName($filepath, 2, '/'); // files/invoices/543287423987542357237538823.pdf
echo "\r\n--------------\r\n".print_r(compact('filepath','alpha','bravo','charlie','delta'),true);
// see working example at ---> https://onlinephp.io/c/62684
@collei
Copy link
Author

collei commented Jun 2, 2023

you can test it at:

https://onlinephp.io/c/62684

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment