Extracting YAML Frontmatter from Documents
Explore methods to extract YAML frontmatter from documents using Laravel and PHP. Learn to split strings with regular expressions, use preg_match_all, and handle offsets to separate frontmatter from content efficiently.
When working with text formats, such as Markdown, it is widespread to come across the concept of YAML frontmatter. These frontmatter documents are a section of the otherwise standard Markdown or similar file with a YAML document embedded at the top of the file. This usually looks like the example found in the code snippet below:
From above, we can note that the YAML frontmatter is typically delimited from the rest of the document by having a line containing --- that surrounds the frontmatter. Splitting an input string into its YAML frontmatter and content is relatively trivial. However, it is also simple enough that we can use it to discuss some other exciting string-splitting techniques.