douchun1900 2018-04-12 06:08
浏览 218
已采纳

PHP文件操作,跳过空行

I have a txt file generated by an instrument. The file needs some sanitation before the data is read into a mysql table. I have done this. But now due to some problem the data generated by the instruments contains empty lines in between and I want to remove it.

At present this is the code

 $target=$_FILES["report_file"]["tmp_name"];        
$file_contents = file_get_contents($target);
$file_contents = str_replace("?","",$file_contents);
$file_contents = str_replace(" ","",$file_contents);
$file_contents = str_replace("","",$file_contents);
$file_contents = str_replace("~","",$file_contents);
$file_contents = str_replace("","",$file_contents);
$file_contents = str_replace("#","",$file_contents);
$file_contents = str_replace(","," ",$file_contents);


file_put_contents($target,$file_contents);

$f = fopen($target, "r");

Can I use file_skip_empty_lines with file_put_contents? of how to put contents without empty lines?

  • 写回答

1条回答 默认 最新

  • doushu5805 2018-04-12 06:13
    关注

    You can trim empty lines using preg_replace

    Trim whitespaces at the beginning of line

    $file_contents = preg_replace("!^s+!m", "", $file_contents);
    

    Remove empty lines

    $file_contents = preg_replace("![
    ]+\s*[
    ]+!", "
    ", $file_contents);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch