Files or strings in DOS format may have \r (carriage return) along with \n (newline). This may appear as ^M in some editors.
Here is quick php code snippet to convert dos newline to unix format:
<?php function dostounix($old) { $new = preg_replace('/\r\n?/', "\n", $old); return $new; } $old = "line1\r\nline2\nline3\r"; $new = dostounix($old); echo "old: " . json_encode($old) . "\n"; echo "new: " . json_encode($new) . "\n"; ?>
old: "line1\r\nline2\nline3\r" new: "line1\nline2\nline3\n"
Env: PHP 7.4.33 (Linux)
Few points to note
- If there is only \r in any line (no \n), it will also be replaced with newline.
- If there is \r\n in any line, it will be replaced with one newline.
- Due to greedy match by default, regex will match both \r\n whenever possible. So presence of \r\n would not cause two newlines.