Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6951083
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T14:10:28+00:00 2026-05-27T14:10:28+00:00

I am trying to do the following with PHP… Read a directory Find all

  • 0

I am trying to do the following with PHP…

  1. Read a directory
  2. Find all .md and .markdown files
  3. Read the first 2 lines of these Markdown files.
  4. If a Title: Title for the file is found on line 1 then add it to the array
  5. If a Description: Short description is found on line 2 then add it to the array
  6. If a Sub-directory is found, repeat steps 1-5 on them
  7. Should now have a nice list/array
  8. Print this list/array to screen to show up like this….

Directory 1 Name

<a href="LINK TO MARKDOWN FILE 1"> TITLE from line 1 of Markdown FILE 1</a> <br>
Description from Markdown FILE 1 line 2

<a href="LINK TO MARKDOWN FILE 2"> TITLE from line 1 of Markdown FILE 1</a> <br>
Description from Markdown FILE 2 line 2

<a href="LINK TO MARKDOWN FILE 3"> TITLE from line 1 of Markdown FILE 1</a> <br>
Description from Markdown FILE 3 line 2

Directory 2 Name

<a href="LINK TO MARKDOWN FILE 1"> TITLE from line 1 of Markdown FILE 1</a> <br>
Description from Markdown FILE 1 line 2

<a href="LINK TO MARKDOWN FILE 2"> TITLE from line 1 of Markdown FILE 1</a> <br>
Description from Markdown FILE 2 line 2

<a href="LINK TO MARKDOWN FILE 3"> TITLE from line 1 of Markdown FILE 1</a> <br>
Description from Markdown FILE 3 line 2

etc..........

Code so far

function getFilesFromDir($dir)
{
    $files = array();
    //scan directory passsed into function
    if ($handle = opendir($dir)) {
        while (false !== ($file = readdir($handle))) {

            // If file is .md or .markdown continue
            if (preg_match('/\.(md|markdown)$/', $file)) {

                // Grab first 2 lines of Markdown file
                $content = file($dir . '/' . $file);
                $title = $content[0];
                $description = $content[1];

                // If first 2 lines of Markdown file have a 
                // "Title: file title" and "Description: file description" lines we then
                // add these key/value pairs to the array for meta data

                // Match Title line
                $pattern = '/^(Title|Description):(.+)/';
                if (preg_match($pattern, $title, $matched)) {
                    $title = trim($matched[2]);
                }

                // match Description line 
                if (preg_match($pattern, $description, $matched)) {
                    $description = trim($matched[2]);
                }

                // Add .m and .markdown files and folder path to array
                // Add captured Title and Description to array as well
                $files[$dir][] = array("filepath" => $dir . '/' . $file,
                                       "title" => $title,
                                       "description" => $description
                                    );

            }
        }
        closedir($handle);
    }

    return $files;
}

Usage

$dir = 'mdfiles';
$fileArray = getFilesFromDir($dir);

Help needed

So far the code just needs to add the ability to do what it does on sub-directories and the way that it matches the first 2 lines of code and then runs the regex 2 times, can probably be done differently?

I would think there is a better way so that the REGEX I have to match the Title and Description can be run just once?

Can someone help me modify to make this code detect and run on sub-directories as well as improve the way it reads the first 2 lines of a markdown file to get the title and description if they exist?

Also need help printing the array to screen to make it not only just show the dat, I know how to do that but has to break the files up to show the Folder name at the top of each set like in my demo output above.

I appreciate any help

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T14:10:28+00:00Added an answer on May 27, 2026 at 2:10 pm

    To recursively iterate over files, the RecursiveDirectoryIterator is quite handy (related: PHP recursive directory path). It already offers an easy access to FileSystemObject as well which looks useful in your case as you want to obtain the files content.

    Additionally it’s possible to run one regular expression to parse the first two lines of the file, as patterns get cached when you execute them more often, it should be fine. One pattern has the benefit that the code is more structured, but the downside that the pattern is more complex. Configuration could look like this:

    #
    # configuration
    #
    
    $path = 'md';
    $fileFilter = '~\.(md|markdown)$~';
    $pattern = '~^(?:Title: (.*))?(?:(?:\r\n|\n)(?:Description: (.*)))?~u';
    

    Just in case the markdown files are actually UTF-8 encoded, I added the u-modifier (PCRE8).

    The processing part of the code is then using a recursive directory iterator over $path, skips files not matching $fileFilter and then parses the first two lines of each file (if a file is at least readable and has at least one line) and stores it into a directory based hashtable/array $result:

    #
    # main
    #
    
    # init result array (the nice one)
    $result = array();
    
    # recursive iterator for files
    $iterator = new RecursiveIteratorIterator(
                   new RecursiveDirectoryIterator($path, FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO), 
                   RecursiveIteratorIterator::SELF_FIRST);
    
    foreach($iterator as $path => $info)
    {
        # filter out files that don't match
        if (!preg_match($fileFilter, $path)) continue;
    
        # get first two lines
        try
        {
            for
            (
                $maxLines = 2,
                $lines = '',
                $file = $info->openFile()
                ; 
                !$file->eof() && $maxLines--
                ; 
                $lines .= $file->fgets()
            );
            $lines = rtrim($lines, "\n");
    
            if (!strlen($lines)) # skip empty files 
                continue;
        }
        catch (RuntimeException $e)
        {
            continue; # files which are not readable are skipped.
        }
    
        # parse md file
        $r = preg_match($pattern, $lines, $matches);
        if (FALSE === $r)
        {
            throw new Exception('Regular expression failed.');
        }
        list(, $title, $description) = $matches + array('', '', '');
    
        # grow result array
        $result[dirname($path)][] = array($path, $title, $description);
    }
    

    What’s left is the output. As the hashtable is pre-ordered by the directory hash, it’s fairly straight forward by first iterating over the directories and then over the files within:

    #
    # output
    #
    
    $dirCounter = 0;
    foreach ($result as $name => $dirs)
    {
        printf("Directory %d %s\n", ++$dirCounter, basename($name));
        foreach ($dirs as $entry)
        {
            list($path, $title, $description) = $entry;
            printf("<a href='%s'>%s from line 1 of Markdown %s</a> <br>\n%s\n\n", 
                    htmlspecialchars($path), 
                    htmlspecialchars($title),               
                    htmlspecialchars(basename($path)),
                    htmlspecialchars($description)
                  );
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to list all the files included in folder using following php
I'm trying use mod_rewrite to rewrite URLs from the following: http://www.site.com/one-two-file.php to http://www.site.com/one/two/file.php The
I'm trying the following command in PHP 5.2.12 : print (date('Y-m-d', strtotime('2009-12 last day')));
I am trying the following code: <?php $link = mysql_connect('localhost', 'root', 'geheim'); if (!$link)
Trying to run the following command in php to run powershell command... the following
I am new to PHP and trying to get the following code to work:
I am trying to do the following: <?php foreach($sqlResult as $row): ?> <tr> <?php
I am trying to teach myself MySQL/PHP from the very beginning. The following code
I'm trying to create css buttons by using the following html markup: <a href=access.php
Am trying the following php script which finds out the maximum between 2 numbers,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.