Skip to content

Instantly share code, notes, and snippets.

Last active Feb 28, 2022
What would you like to do?
Renumbers footnotes in a markdown file in sequential order
// 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 "" by default
// Original text with renumbered footnotes will be saved in ""
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 = "";
$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('', "w+");
fwrite($output, $newfile);
echo ("done");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment