首页 > 解决方案 > PHP 在文本文件中查找一行并删除该行

问题描述

我有一个文本文件,其中包含一堆文本,格式为

经纬度时间

22.300859182388606 -127.66133104264736 1528577039
22.30103320995603 -127.66234927624464 1528577041
22.300184137952726 -127.661628767848 1528577042
22.29943548054545 -127.66242001950741 1528577045

我得到了坐标,我想在文本文件中搜索相同的坐标,如果有,从文件中删除该行。如何搜索与给定坐标相同的坐标并将其从文件中删除?这是我到目前为止的代码:

<?php
$msg = $_GET["coords"];
$file = 'coordinates.txt';
// Open the file to get existing content
$current = file_get_contents($file);

?>

标签: php

解决方案


看到您创建的代码看起来很有趣。顺便说一句,我通过评论进行了解释。

假设 :

yourfile.php?coords=22.300859182388606 -127.66133104264736

// Assumption : 
// 22.300859182388606 -127.66133104264736
$msg = isset($_GET['coords']) ? $_GET['coords'] : null;

if ($msg) {
    $file = 'coordinates.txt';
    // Change newline into array
    $items = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $new   = [];

    foreach ($items as $key => $item) {
        // Remove time
        // Yep, I see you're using unixtime (10 characters + 1 space)
        $check = substr($item, 0, -11);

        // If $msg === $check, append to $new
        if (strpos($check, $msg) === false) {
            $new[] = $item;
        }
    }

    // If $new has value
    if ($new) {
        // Write file with $new content
        file_put_contents($file, implode("\n", $new));
    }
}

推荐阅读