Created
December 11, 2022 15:44
-
-
Save AucT/b6120f937ac59d6e4a08848562b5fb65 to your computer and use it in GitHub Desktop.
copy this script to hugo content/posts folder and run php rename_files.php and you will get nicely named files with date prefix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//copy this script to hugo content/posts folder and run php rename_files.php and you will get nicely named files with date prefix | |
if (!function_exists('str_ends_with')) { | |
function str_ends_with(string $haystack, string $needle): bool | |
{ | |
$needle_len = strlen($needle); | |
return ($needle_len === 0 || 0 === substr_compare($haystack, $needle, -$needle_len)); | |
} | |
} | |
$dir = new DirectoryIterator(dirname(__FILE__)); | |
foreach ($dir as $fileinfo) { | |
if ($fileinfo->isDot()) { | |
continue; | |
} | |
if (!str_ends_with($fileinfo->getFilename(), '.md')) { | |
continue; | |
} | |
$markdownOfFile = file_get_contents($fileinfo->getFilename()); | |
preg_match_all('/title:(.*?)$/m', $markdownOfFile, $output_array); | |
$title = $output_array[1][0] ?? null; | |
$slug = null; | |
if ($title) { | |
$title = trim($title); | |
$title = trim($title,'"'); | |
$slug = slugify($title); | |
$slug = substr($slug, 0, 60); | |
} | |
preg_match_all('/date:(.*?)$/m', $markdownOfFile, $output_array); | |
$date = $output_array[1][0] ?? null; | |
if ($date) { | |
$date = trim($date); | |
$date = substr($date, 0, 10); | |
} | |
$newFileName = "{$date}_{$slug}.md"; | |
echo PHP_EOL . $newFileName; | |
if ($date && $title) { | |
rename($fileinfo->getFilename(), $newFileName); | |
} | |
} | |
function slugify($text, string $divider = '-') | |
{ | |
// remove unwanted characters (my) | |
$text = str_replace(['"', '\''], '', $text); | |
// replace non letter or digits by divider | |
$text = preg_replace('~[^\pL\d]+~u', $divider, $text); | |
// transliterate | |
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); | |
// remove unwanted characters | |
$text = preg_replace('~[^-\w]+~', '', $text); | |
// trim | |
$text = trim($text, $divider); | |
// remove duplicate divider | |
$text = preg_replace('~-+~', $divider, $text); | |
// lowercase | |
$text = strtolower($text); | |
if (empty($text)) { | |
return 'n-a'; | |
} | |
return $text; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment