Last active
March 28, 2016 22:22
-
-
Save swichers/97c1ece443e75c54019f to your computer and use it in GitHub Desktop.
Quick and dirty markdown link checker
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 | |
function get_markdown_files($dir = '.') { | |
$directory = new RecursiveDirectoryIterator($dir); | |
$recursive = new RecursiveIteratorIterator($directory); | |
$regex = new RegexIterator($recursive, '/^.+\.md/i', RecursiveRegexIterator::GET_MATCH); | |
$files = array(); | |
foreach ($regex as $file) { | |
if (!empty($file[0])) { | |
$files[] = $file[0]; | |
} | |
} | |
return $files; | |
} | |
function get_md_links_from_file($file) { | |
$links = array(); | |
$contents = file_get_contents($file); | |
if (preg_match_all('/\[(.+?)\].*?\((.+?)\)/', $contents, $matches, PREG_SET_ORDER)) { | |
$links = array_merge($links, $matches); | |
} | |
return $links; | |
} | |
$files = get_markdown_files(); | |
foreach ($files as $file) { | |
$links = get_md_links_from_file($file); | |
foreach ($links as $link) { | |
$path = $link[2]; | |
if (preg_match('/^(http|#)/', $path)) { | |
continue; | |
} | |
$path = current(explode('#', $path, 2)); | |
$start = rtrim(__DIR__, '/'); | |
if ($path[0] !== '/') { | |
$start .= '/' . rtrim(dirname($file), '/'); | |
} | |
$realpath = realpath($start . '/' . $path); | |
if (empty($realpath) || (!file_exists($realpath) && !is_dir($realpath))) { | |
printf("%s: Possible bad link for \"%s\" to \"%s\"\n", $file, $link[1], $link[2]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment