2

I have a file that I have to read in and modify in PHP, and so I read it in, explode it by new lines, modify what I need, then re-stick it together re-adding newlines via \n.

However, it seems to be outputting them as \r\\n for some reason. The file before any modification has new lines as \r\n which seems to work fine. Only when I add the new lines via \n does it break into \r\\n.

Also after some reading, I tried the newlines as \r\n instead of just \n, but that outputs as \r\\r\\n. Any ideas guys? Thanks a lot! If you need to see anything else or require more info, just ask.

The code that add's the new lines is here:

for($i = 0 ; $i<count($tmp);$i++){
        $tmpstr .= $tmp[$i];
        if(count($tmp)-1 != $i){
            $tmpstr .= '\r\n';
        }
    }

It adds newlines at the end of all but the last line, that seems to be working fine except for the wrong characters.

aefxx
  • 24,835
  • 6
  • 45
  • 55
samuraiseoul
  • 2,888
  • 9
  • 45
  • 65
  • are you splitting your string up with `explode("\n", $string);`? If so, just split it up with `explode("\r\n", $string);`, or do a str_replace("\r","", $string); – Green Black Dec 01 '12 at 00:26
  • 4
    Replace your loop with: `$tmpstr = implode("\r\n", $tmp);`. [Ta-da!](http://codepad.org/ceLz3KnK) – NullUserException Dec 01 '12 at 00:27

3 Answers3

4

Change $tmpstr .= '\r\n';
To: $tmpstr .= "\r\n" # Use double quotes;

Anil
  • 21,730
  • 9
  • 73
  • 100
  • Thanks that worked, are there any other times I need to be careful of quotes vs apostrophes? – samuraiseoul Dec 01 '12 at 00:39
  • theres a great answer here: http://stackoverflow.com/questions/3446216/difference-between-single-quote-and-double-quote-string-in-php – Anil Dec 01 '12 at 22:43
2

you have to use double quotes "\r\n"

mychalvlcek
  • 3,956
  • 1
  • 19
  • 34
1

You can also use the predefined constant PHP_EOL (End Of Line):

$tmpstr .= PHP_EOL;
HamZa
  • 14,671
  • 11
  • 54
  • 75