本文實例講述了PHP實現(xiàn)逐行刪除文件右側空格的方法。分享給大家供大家參考,具體如下:
在編輯整理代碼的過程中發(fā)現(xiàn)網(wǎng)上的一些代碼經(jīng)常會有不少的右側空格,偶爾會影響到代碼的排版與閱讀,所以寫了一段簡單的php代碼來逐行刪除文件右側的空格,并保存到新的文件中。
帶有右側空格的demo.txt文件(該文件是PHP逐行讀取功能代碼)如下:
1
2
3
4
5
6
7
|
$file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "< br />"; } fclose($file); |
PHP逐行刪除右側空格代碼如下:
1
2
3
4
5
6
7
8
9
|
<?php $file =@ fopen ( "demo.txt" , "r" ) or exit ( "file don't exit" ); $tmpstr = "" ; while (! feof ( $file )){ $tmpstr .= rtrim( fgets ( $file )). "\n" ; } fclose( $file ); file_put_contents ( "filetmp.txt" , $tmpstr ); ?> |
運行后即可將刪除右側空格后的文件保存到filetmp.txt
補充:
還可以將帶有右側空格的文件在eclipse環(huán)境下編輯保存,不需要代碼即可自動刪除右側空格。更加方便。
希望本文所述對大家PHP程序設計有所幫助。