Created
July 21, 2014 02:53
-
-
Save yuanqing/dfa62c8274a7ce19c2c2 to your computer and use it in GitHub Desktop.
PHP: Parsing YAML Frontmatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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