我正在尝试从txt文件中删除包含空格的行。我的代码已经删除了重复的行,但是如何同时删除包含空格的整行?
$lines = file('myFile.txt');
$lines = array_unique($lines);
file_put_contents('myFile.txt', implode($lines));
答案 0 :(得分:0)
- 如果我的问题是对的,则需要删除包含带有空格和空白行的单词的行。
- 当您获得一个行数组时,您可以简单地遍历它并检查它是否包含空格;如果是这样,请删除该数组元素。
这是您的情况的简单再现-
<?php
$lines = ["LoremIpsuissimplydummytextoftheprintingandtypesettingindustry.",
"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,",
"when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,",
"but also the leap into electronic typesetting, remaining essentially unchanged.",
"It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,",
"and more recently with desktop publishing"];
foreach($lines as $k => $v) {
if(preg_match('/\s+/', $v)) {
unset($lines[$k]);
}
}
var_dump($lines);
?>
此代码将删除所有带有一个或多个连续空格的行。因此,它将仅输出没有空格的行-
array(1) { [0]=> string(62) "LoremIpsuissimplydummytextoftheprintingandtypesettingindustry." }