Skip to content

Instantly share code, notes, and snippets.

@yuanqing
Created July 21, 2014 02:53
Show Gist options
  • Save yuanqing/dfa62c8274a7ce19c2c2 to your computer and use it in GitHub Desktop.
Save yuanqing/dfa62c8274a7ce19c2c2 to your computer and use it in GitHub Desktop.
PHP: Parsing YAML Frontmatter
<?php
# 10,000 iterations in 1.9696619510651s
function frontMatterExplode($str)
{
$lines = explode(PHP_EOL, $str);
if (rtrim($lines[0]) === '---') {
unset($lines[0]);
$i = 1;
$yaml = array();
foreach ($lines as $line) {
if (rtrim($line) === '---') {
break;
}
$yaml[] = $line;
$i++;
}
$yaml = implode(PHP_EOL, $yaml);
$content = implode(PHP_EOL, array_slice($lines, $i));
return array(trim($yaml), trim($content));
}
return array('', $str);
}
# 10,000 iterations in 3.0784578323364s
function frontMatterRegex($str)
{
$matches = array();
if (preg_match('/^---\s*\n(.*?)\n---\s*\n(.*?)$/s', $str, $matches)) {
return array(trim($matches[1]), trim($matches[2]));
}
return array('', $str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment