php - 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);
?>
解决方案
看到您创建的代码看起来很有趣。顺便说一句,我通过评论进行了解释。
假设 :
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));
}
}
推荐阅读
- matlab - Matlab:情节到子情节
- jmeter - Jmeter 多个 CSV 文件
- javascript - 在另一个jsp文件的div块中加载包含html的本地jsp文件
- xml - PDF 视图 (XSLT) 中缺少 CALS 表格边框线
- typescript - Typescript with Angular HttpClient ErrorType ...在调用类方法时不是函数
- arrays - 如何将 *big.Int 转换为 golang 中的字节数组
- android - Android Activity 是在应用程序进程中启动的,尽管它是从其他进程开始的
- python - Python - 我可以用 for 循环打印出具有连续数字的变量吗?
- vue.js - 如何使用 vuex 通过 vuejs 中的道具获取状态项
- angular - 如何在角度 4 中执行搜索功能?