PHP – convert dos newline to unix format

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:

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 5.5.9 (Linux)

Few points to note

  1. If there is only \r in any line (no \n), it will also be replaced with newline.
  2. If there is \r\n in any line, it will be replaced with one newline.
  3. Due to greedy match by default, regex will match both \r\n whenever possible. So presence of \r\n would not cause two newlines.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments