【发布时间】:2020-08-10 05:09:17
【问题描述】:
我正在尝试格式化以下文件;
[30-05-2013 15:45:54] A A
[26-06-2013 14:44:44] B A
[26-06-2013 14:44:44] C A
[26-06-2013 14:43:16] Some lines are so large, they take multiple lines, so explode('\n') won't work because
I need the complete message
[26-06-2013 14:44:44] E A
[26-06-2013 14:44:44] F A
[26-06-2013 14:44:44] G A
预期输出:
Array
(
[0] => [30-05-2013 15:45:54] A A
[1] => [26-06-2013 14:44:44] B A
[2] => [26-06-2013 14:44:44] C A
[3] => [26-06-2013 14:43:16] Some lines are so large, they take multiple lines, so
explode('\n') won't work because
I need the complete message
[4] => [26-06-2013 14:44:44] E A
...
)
基于How do I include the split delimiter in results for preg_split()?,我尝试使用积极的后视来保留时间戳并提出Regex101:
(?<=\[)(.+)(?<=\])(.+)
在以下PHP代码中使用;
#!/usr/bin/env php
<?php
class Chat {
function __construct() {
// Read chat file
$this->f = file_get_contents(__DIR__ . '/testchat.txt');
// Split on '[\d]'
$r = "/(?<=\[)(.+)(?<=\])(.+)/";
$l = preg_split($r, $this->f, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
var_dump(count($l));
var_dump($l);
}
}
$c = new Chat();
这给了我以下输出;
array(22) {
[0]=>
string(1) "["
[1]=>
string(20) "30-05-2013 15:45:54]"
[2]=>
string(4) " A A"
[3]=>
string(2) "
["
[4]=>
string(20) "26-06-2013 14:44:44]"
[5]=>
string(4) " B A"
[6]=>
string(2) "
["
[7]=>
string(20) "26-06-2013 14:44:44]"
[8]=>
string(4) " C A"
[9]=>
string(2) "
["
[10]=>
string(20) "26-06-2013 14:43:16]"
[11]=>
string(87) " Some lines are so large, they take multiple lines, so explode('\n') won't work because"
[12]=>
string(30) "
I need the complete message
["
问题
- 为什么第一个
[会被忽略? - 我应该如何更改正则表达式以获得所需的输出?
- 为什么会有带有
PREG_SPLIT_NO_EMPTY的空字符串?
【问题讨论】:
-
this 是否适合您 -
(\[.*?\])([^\[]+)?
标签: php regex preg-split