栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用php替换文本文件中的特定行?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用php替换文本文件中的特定行?

您可以在较小的文件上使用一种方法,该文件可以两次装入您的内存:

$data = file('myfile'); // reads an array of linesfunction replace_a_line($data) {   if (stristr($data, 'certain word')) {     return "replaement line!n";   }   return $data;}$data = array_map('replace_a_line',$data);file_put_contents('myfile', implode('', $data));

快速说明,PHP> 5.3.0支持lambda函数,因此您可以删除命名的函数声明并将映射缩短为:

$data = array_map(function($data) {  return stristr($data,'certain word') ? "replacement linen" : $data;}, $data);

从理论上讲,您可以使它成为单个(很难理解)的php语句:

file_put_contents('myfile', implode('',   array_map(function($data) {    return stristr($data,'certain word') ? "replacement linen" : $data;  }, file('myfile'))));

您应该对较大的文件使用另一种(较少占用内存的方法):

$reading = fopen('myfile', 'r');$writing = fopen('myfile.tmp', 'w');$replaced = false;while (!feof($reading)) {  $line = fgets($reading);  if (stristr($line,'certain word')) {    $line = "replacement line!n";    $replaced = true;  }  fputs($writing, $line);}fclose($reading); fclose($writing);// might as well not overwrite the file if we didn't replace anythingif ($replaced) {  rename('myfile.tmp', 'myfile');} else {  unlink('myfile.tmp');}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465898.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号