PHP-从父字符串中删除以特定字符开头和结尾的子字符串

时间:2019-03-03 19:11:23

标签: php

我有两个文件,index.md和subPage.md。这是文件index.md:

---
Title: Index page
Description: This is a sample description.
Keywords: Those, are, keywords.
Template: index
---
# Hello!
This is an Index.md file.

这是sub.md:

---
Title: Sub Page
---
# Again hello
Lorem ipsum dolor sit amet.

在文件index.php上,我正在获取这些文件的内容:

$indexPage = file_get_contents(__DIR__ . '/index.md');
$subPage = file_get_contents(__DIR__ . '/subPage.md');

我需要删除每个文件中以 --- 开头和结尾的代码段。问题在于PHP文件必须检测两个文件中以这三个字符开头和结尾的子字符串。我该怎么办?

预先感谢:)

1 个答案:

答案 0 :(得分:2)

您可以为此使用正则表达式,请尝试以下一种:https://regexr.com/49l2p

这是快速的代码示例:

<?php

$indexPage = file_get_contents(__DIR__ . '/index.md');
$subPage = file_get_contents(__DIR__ . '/subPage.md');

$pattern = '/^---\n[\w\W]+---\n/m';

$indexReplaced = preg_replace($pattern, '', $indexPage);
$subPageReplaced = preg_replace($pattern, '', $subPage);

var_dump($indexReplaced, $subPageReplaced);

该模式首先在字符串的开头寻找---,然后寻找之后的所有内容,最后寻找第二个---,然后寻找新的一行。非常简单的regexp:)