php - 仅在不匹配时保存一行
问题描述
我正在尝试从文件中保存数据,以防该行与字符不匹配。就我而言,我有一个数字列表,如果只有第一个字符不等于“0”-零-,我想保存这些数字
这是我的代码:
<?php
$cleanfile = "cleanfile.txt";
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if ($line[0] != 0) {
$save = file_put_contents($cleanfile, $line);
}
}
fclose($handle);
} else {
// error opening the file.
}
我的 file.txt 有以下条目:
1
2
3457
94
31
54
039
3114
94
01
33333
1
2
3457
94
31
54
039
3114
94
01
33333
1
2
3457
94
31
54
039
3114
94
01
33333
解决方案
您需要将FILE_APPEND
标志传递给file_put_contents()
,如下所示:
<?php
$cleanfile = "cleanfile.txt";
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if ($line[0] != 0) {
$save = file_put_contents($cleanfile, $line, FILE_APPEND);
}
}
fclose($handle);
} else {
// error opening the file.
}
但是,您的解决方案有点耗费资源,因为每次调用都会file_put_contents()
产生不必要的开销。请将此演示视为更轻、更紧凑的解决方案:
<?php
// Collect all non-filtered lines.
$sieved = [];
// Read file.txt into an array, skipping empty lines.
foreach (file('file.txt', FILE_SKIP_EMPTY_LINES) as $line)
{
if ($line[0] !== '0')
$sieved[] = $line;
}
// Write out each array element, keeping the newlines from the input.
file_put_contents('cleanfile.txt', $sieved);
推荐阅读
- javascript - 如何将每个循环变量值推入数组
- javascript - JSON。JAVA 和 PHP 检查表单值是否存在
- solr - SOLR - 从给定搜索请求的相交多边形中获取所有文档条目
- java - 不是一个文件中的 JSON 对象异常,但不同的 json 文件有效
- postgresql - Symfony 4 + Api 平台无法自动验证类型为“NULL”的值。在 nativeSQL 查询上
- c - 计算一个数字的除数的最佳算法是什么?
- python - 字符串中两个字母之间的距离
- docker - Traefik 未将请求路径传递给 Strapi CMS
- git - svn:从远程 git 存储库的特定提交中导出文件夹
- react-native - React Native Modal:透明背景和布局问题