forked from philsturgeon/phptherightway-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.php
61 lines (43 loc) · 1.82 KB
/
convert.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
$dirName = './web/_posts';
$outputDirName = './manuscript';
$dir = new DirectoryIterator($dirName);
$contentArray = [];
foreach ($dir as $fileinfo) {
if (!$fileinfo->getExtension() == 'md') {
continue;
}
// Split the 00-00-00-Some-Content.md name into useful info
preg_match('#(\d+)-(\d+)-(\d+)-([^\.]+).md#', $fileinfo->getFilename(), $nameParts);
list(, $chapter, $section, $subSection, $chapterName) = $nameParts;
echo "$chapter-$section-$subSection-$chapterName\n";
$chapter = (int) $chapter;
// Create this new chapter
if (empty($contentArray[$chapter])) {
$contentArray[$chapter] = '';
}
// Take this sub-section and shove it into the chapter content
$subSectionContent = file_get_contents($dirName.'/'.$fileinfo->getFilename());
// Strip the header out if there is one
preg_match('/^---[\s\S]*?---/', $subSectionContent, $subSectionMatches);
if (isset($subSectionMatches[0])) {
$subSectionContent = str_replace($subSectionMatches[0], '', $subSectionContent);
}
// Switch the syntax highlighter
$subSectionContent = preg_replace('/{% highlight (\S+) %}/', "\n{lang=\"\$1\"}\n~~~~~~~~", $subSectionContent);
$subSectionContent = str_replace([
'{% endhighlight %}',
'(/pages/', // Convert links to pages
], [
'~~~~~~~~',
'(http://phptherightway.com/pages/'
], $subSectionContent);
$contentArray[$chapter] .= $subSectionContent;
}
$bookTxtContent = "";
// Now output all that info to new markdown files
foreach ($contentArray as $chapterNum => $chapterContent) {
file_put_contents("{$outputDirName}/converted/chapter{$chapterNum}.txt", $chapterContent);
$bookTxtContent .= "converted/chapter{$chapterNum}.txt\n";
}
file_put_contents("{$outputDirName}/Book.txt", $bookTxtContent);