我有YAML Front Matter,我想用PHP解析:
---
title = A nice title goes here
tags = tag1 tag2 tag3
---
This is the content of this entry...
Line2
Line3
Run Code Online (Sandbox Code Playgroud)
我知道它是关于某种类型的Ruby gem,但我想在PHP中使用它来创建一个用户友好的flatfile博客引擎.
我还有一个名为Phrozn的项目片段.也许为了帮助我尽可能地解决问题,你们可以方便地看到它.
private function parse()
{
if (isset($this->template, $this->frontMatter)) {
return $this;
}
$source = $this->readSourceFile();
$parts = preg_split('/[\n]*[-]{3}[\n]/', $source, 2);
if (count($parts) === 2) {
$this->frontMatter = Yaml::load($parts[0]);
$this->template = trim($parts[1]);
} else {
$this->frontMatter = null;
$this->template = trim($source);
}
return $this;
}
Run Code Online (Sandbox Code Playgroud)
我认为你的问题是你试图将三个部分分成两部分.如果你删除第三个参数preg_split,你将得到一个包含三个元素的数组.第一部分(当分隔时---):
---
title = A nice title goes here
tags = tag1 tag2 tag3
---
This is the content of this entry...
Line2
Line3
Run Code Online (Sandbox Code Playgroud)
是空的,第二个是YAML,第三个是内容.试试这个:
$parts = preg_split('/[\n]*[-]{3}[\n]/', $source, 3);
Run Code Online (Sandbox Code Playgroud)
还有一个实时测试案例:http://ideone.com/LYLxZ
如果你想匹配Phrozn似乎正在做的事情,那么你的输入将如下所示:
title = A nice title goes here
tags = tag1 tag2 tag3
---
This is the content of this entry...
Line2
Line3
Run Code Online (Sandbox Code Playgroud)
而你的PHP将是这样的:
$parts = preg_split('/[\n]*[-]{3}[\n]/', $source, 2);
Run Code Online (Sandbox Code Playgroud)
这个版本的实时测试用例:http://ideone.com/a9a6C