简体   繁体   English

PHP按日期将字符串拆分为数组(yyyy-mm-dd)

[英]php split string into array by date (yyyy-mm-dd)

I have a plain text journal I'm trying to format in php. 我有一个纯文本日记,我试图用php格式化。 I'd like to split each entry into an array containing date and text. 我想将每个条目拆分为一个包含日期和文本的数组。

Using preg_split I can do this, however it removes the date altogether! 使用preg_split我可以做到这一点,但是它完全删除了日期!

The txt file looks something like this: txt文件如下所示:

2012-01-28

text text text

2012-01-14

some other text

2011-12-07

a previous entry

etc. 等等

By all means you can preg_match_all : 一定可以preg_match_all

$matches = array();
preg_match_all('~(?P<date>\d{4}-\d{2}-\d{2})\s*(?P<text>.*)~ms', $subject, $matches);

Might need to meddle with it a bit to fit your content. 可能需要混入一点以适合您的内容。

Results into a structure like 结果变成一个像

matches => {
    date(3) => {"2012-01-28", ... }
    ...
    text(3) => {"text text text", ...}

which can easily be utilized or transformed into custom sctructure. 可以轻松利用或转化为自定义结构。

the PREG_SPLIT_DELIM_CAPTURE flag will prevent your dates from being removed when you split, as long as the date is parenthesized in your pattern string. PREG_SPLIT_DELIM_CAPTURE标志将防止您在拆分时删除日期,只要在模式字符串中用括号括起日期即可。 eg: 例如:

$array = preg_split('/(\d{4}-\d{2}-\d{2})/', $text, null, PREG_SPLIT_DELIM_CAPTURE);

Now your dates are in the odd indices of the array and your content is in the even indices. 现在,您的日期在数组的奇数索引中,而您的内容在偶数索引中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM