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 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?