From b4ebfb47190f386da62d233b18a26ebb1f7f217f Mon Sep 17 00:00:00 2001 From: filesite Date: Sun, 27 Mar 2022 18:58:59 +0800 Subject: [PATCH] function getMDTitles done --- lib/DirScanner.php | 21 +++++++++++++++++++++ test/DirScannerTest.php | 15 +++++++++++---- test/init_test_files.sh | 17 +++++++++++++++++ 3 files changed, 49 insertions(+), 4 deletions(-) diff --git a/lib/DirScanner.php b/lib/DirScanner.php index 6a629ee..6fb4a8b 100644 --- a/lib/DirScanner.php +++ b/lib/DirScanner.php @@ -516,4 +516,25 @@ Class DirScanner { return $menus; } + //获取.md文件中的h1-h6标题 + public function getMDTitles($id) { + $file = $this->scanResults[$id]; + if (empty($file)) {return [];} + + $titles = []; + $content = file_get_contents($file['realpath']); + preg_match_all('/#(.+)/u', $content, $matches); + if (!empty($matches[1])) { + foreach($matches[1] as $title) { + $num = substr_count($title, '#'); + $titles[] = [ + 'name' => trim(str_replace('#', '', $title)), + 'heading' => 'h' . ($num+1), + ]; + } + } + + return $titles; + } + } diff --git a/test/DirScannerTest.php b/test/DirScannerTest.php index 545c049..58b26c3 100644 --- a/test/DirScannerTest.php +++ b/test/DirScannerTest.php @@ -70,16 +70,23 @@ $dirTree = $scanner->scan(__DIR__ . '/content/', 4); echo "Time cost: {$scanner->scanTimeCost} ms\n"; echo "\n"; -$menus = $scanner->getMenus(); -print_r($menus); -echo "\n"; -echo "\n"; +$readme_id = '34528ca632426cd2cd570dd32c9dcf4c'; +$readme_titles = $scanner->getMDTitles($readme_id); +print_r($readme_titles); + +//$menus = $scanner->getMenus(); +//echo "Directories:\n"; +//print_r($menus); +//echo "\n"; +//echo "\n"; +//echo "Directories and files' tree:\n"; //print_r($dirTree); //echo "\n"; //echo "\n"; + //$scanResults = $scanner->getScanResults(); //print_r($scanResults); //echo "\n"; diff --git a/test/init_test_files.sh b/test/init_test_files.sh index cf04303..900cee6 100755 --- a/test/init_test_files.sh +++ b/test/init_test_files.sh @@ -23,9 +23,26 @@ rm -rf content/ mkdir -p content/favs/ cd content/favs/ +rm -f Readme.md rm -rf "小说/" rm -rf "图片/" +touch "Readme.md" +tee -a "Readme.md" <