首页 > 解决方案 > 如何使用php从txt文件中删除带空格的行

问题描述

我正在尝试从 txt 文件中删除包含空格的行。我的代码已经删除了重复的行,但是如何同时删除包含空格的整行?

$lines = file('myFile.txt');
$lines = array_unique($lines);
file_put_contents('myFile.txt', implode($lines));

标签: php

解决方案


  • 如果我的问题正确,您需要删除包含带有空格的单词的行和空行。
  • 当您获得一系列行时,您可以简单地遍历它并检查它是否包含空格;如果是这样,请删除该数组元素。

这是您的场景的简单复制-

<?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." }

推荐阅读