• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 283
  • Last Modified:

Removing line breaks from the file

Hi there,

I have a txt file which is generated in Mac with CRLF line breaks. Now, i am trying to read each line of this file in PC environment (Linux). But i couldn't do it yet, getting mad!

Could you please tell me how can i read from a file until the end of line... I am using the below code to read from the file but it reads all lines :(

$FileHandle = fopen("./mac.txt", "r");
      while (!feof($FileHandle))
            // Read only first line
            $FirstLine = trim(fgets($FileHandle, 4096));

$FirstLine should include only the first line, but it includes all lines. How can i read a line from the file until the end of line (no matter CRLF, LF or CR)

  • 2
  • 2
1 Solution
Marcus BointonCommented:
PHP can handle different line break formats transparently, but you need to enable it:

blacklordAuthor Commented:
Thanks, it is great but i noticed that it works only PHP versions which are higher than PHP v4.3. Do you have any other solutions?

If no, i will accept this as an answer
Wich version of PHP do you use? There were some problems with line endings, but afaik they fixed it in one of the last updates ...
blacklordAuthor Commented:
I am developing a PHP script which must work on multiple platforms with PHP > v4.1 :(

However, i think i will use Squinky's suggestion. Thanks!
Marcus BointonCommented:
if you use a non-line oriented reading function, you can convert line breaks and explode them afterwards. I use this function for preprocessing all kinds of uploaded data - remember that form submissions often come with CRLF line breaks in too:

* Normalise Mac LF and  Windows CRLF line breaks into UNIX CR line breaks
* @param string $text
* @return string
function normalisebreaks($text) {
      return preg_replace('/\r\n|\n\r|\r/', "\n", $text);
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now