Last active
February 28, 2022 03:55
-
-
Save nimdaghlian/d0621557883cd7c463eec59aea3d8e6c to your computer and use it in GitHub Desktop.
Renumbers footnotes in a markdown file in sequential order
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 | |
// This renumbers footnotes in a markdown file in the order they appear, both in the text and citations | |
// Insert new footnotes in the order in which they should appear, in both text and citation | |
// Use a unique identifier for each new footnote ie [^fn1a], [^fn2a], etc. | |
// Place your footnotes at the end of the file with your full text. | |
// Separate them from the main text with the header `# Footnotes` | |
// | |
// This is meant to be run from the command line | |
// Run "php fnprocess.php -fFILENAME.MD" where FILENAME.MD is the name of the input file | |
// If you'd rather not specify a filename, this looks for "input.md" by default | |
// Original text with renumbered footnotes will be saved in "output.md" | |
function updateFootnotes($text){ | |
$regex = '/fn\d{1,3}/'; | |
preg_match_all($regex, $text, $matches); | |
$total = count($matches[0]); | |
// Uncomment the following two lines if you want verbose output | |
// echo ("<h2>".count($matches[0])." matches found</h2>"); | |
// print_r($matches); | |
$patternz = array(); | |
$replacementz = array(); | |
foreach ($matches[0] as $key => $value) { | |
$pat = '/'.$value.'/'; | |
$val = "unique-string-seahorse".(strval($key)+1); | |
array_push($patternz, $pat); | |
array_push($replacementz, $val); | |
} | |
$combined = array_combine($patternz, $replacementz); | |
$combined = array_reverse($combined); | |
foreach ($combined as $pat => $val){ | |
$text = preg_replace($pat, $val, $text); | |
} | |
$updatedText = preg_replace('/unique-string-seahorse/', 'fn', $text); | |
return $updatedText; | |
} | |
// get file contents | |
$options = getopt("f::"); | |
if ($options) { | |
$filename = $options["f"]; | |
} | |
else { | |
$filename = "input.md"; | |
} | |
$maintext = file_get_contents($filename); | |
$textArray = explode("# Footnotes", $maintext); | |
$newfile = ""; | |
foreach($textArray as $key => $value){ | |
if ($key == 2){ | |
$value == substr($value, 12); | |
} | |
$newfile .= updateFootnotes($value); | |
} | |
$output = fopen('output.md', "w+"); | |
fwrite($output, $newfile); | |
fclose($output); | |
echo ("done"); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment