【发布时间】:2018-02-20 10:14:38
【问题描述】:
我有一个文本文件 test.txt:
this is test line
another line
2146554
145648
DATE 2017-12-12
USR-PASSWORD *\#5%*sdfdaw*eewaqd*
TYPE ---NULLS--- TBL
PWD-TOD 2018-01-01
EDBS
18/01/02 KEYFROM
SDBS
在您看到空行的地方,它们实际上包含 3 个空格。我已经能够删除任何包含特定单词的行:
<?php
$file = file('test.txt');
$key = '17.2';
$cleaned = array();
//CLEANUP START
$unwanted_words = array(" DATE", "USR-PASSWORD", "PWD-TOD", "KEYFROM ");
$unwanted_words_match = '(?:' . join('|', array_map(function($word) {
return preg_quote($word, '/');
}, $unwanted_words)) . ')';
$replace_match = '/^.*' . $unwanted_words_match . '.*$[\r\n]/m';
$result = preg_replace($replace_match, '', $file);
foreach ($result as $key => $value) {
if(!empty($value)) {
$cleaned[] = $value;
echo $value . "<br />";
}
}
?>
最后一步是删除那些带有 3 个空格的行。我试过了
\n[ ]{3,}
但我的 reg ex 知识到此为止。
【问题讨论】:
-
我建议你做一个现场演示,因为我们看不到输入字符串。
-
试试
$file = preg_replace('~^ {3}$\R*~m', '', $file) -
如果您指的是任何水平空白,请尝试
preg_replace('~^\h{3}$\R*~um', '', $file),如果可能超过 3 个,请将{3}更改为{3,}。 -
我还建议将
'.*$[\r\n]/m'替换为'.*$\R?/m' -
所以你不应该使用逗号
,量化:{3}并添加$断言行尾:(?m)^[ ]{3}$(这将删除空格但不删除行)将行删除为好吧,你应该这样做:(?m)^[ ]{3}$\R?。这是一个现场演示regex101.com/r/BSQMKj/1