dongyuan9149 2019-02-19 06:45
浏览 129

如何使用PHP [copy]从txt文件中删除带有空格的行

This question already has an answer here:

I am trying to remove lines that contain whitespace from a txt file. My code already removes duplicate lines, but how can I remove entire lines that contain whitespace simultaneously?

$lines = file('myFile.txt');
$lines = array_unique($lines);
file_put_contents('myFile.txt', implode($lines));
</div>
  • 写回答

1条回答 默认 最新

  • dpz1983 2019-02-19 07:04
    关注
    • If I'm getting your question right, you need to remove the lines which contain words with white spaces and the blank lines too.
    • As you are getting an array of lines, you can simply iterate through it & check if it contains spaces; if so, remove that array element.

    Here's a simple reproduction of your scenario -

    <?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);
    ?>
    

    This code will remove all the lines with one or more consecutive white spaces. So, it will output only the lines without spaces -

    array(1) { [0]=> string(62) "LoremIpsuissimplydummytextoftheprintingandtypesettingindustry." }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类