php - 如何使用php从txt文件中删除带空格的行
问题描述
我正在尝试从 txt 文件中删除包含空格的行。我的代码已经删除了重复的行,但是如何同时删除包含空格的整行?
$lines = file('myFile.txt');
$lines = array_unique($lines);
file_put_contents('myFile.txt', implode($lines));
解决方案
- 如果我的问题正确,您需要删除包含带有空格的单词的行和空行。
- 当您获得一系列行时,您可以简单地遍历它并检查它是否包含空格;如果是这样,请删除该数组元素。
这是您的场景的简单复制-
<?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." }
推荐阅读
- sql - 我正在使用带有存储过程的方法,但它总是返回 false
- html - 如何为 IE11 编辑网格模板列
- javascript - 导航栏元素自动隐藏
- c# - 方法“RenderPartial”没有重载需要 3 个参数
- python - Python 类继承:递归错误
- r - coord_sf 强制ggplot网格线?
- unreal-engine4 - 我看不出光照贴图分辨率之间有什么区别
- sql - 加入/合并两个表的日期范围
- javascript - React-express:GET 路由不适用于 href,但 POST 路由适用于表单提交
- python - threading.Timer() 和实例销毁