InfoHeap
Tech
Navigation
  • Home
  • Tutorials
    • CSS tutorials & examples
    • CSS properties
    • Javascript cookbook
    • Linux/Unix Command Line
    • Mac
    • PHP
      • PHP functions online
      • PHP regex
    • WordPress
  • Online Tools
    • Text utilities
    • Online Lint Tools
search
  • Home
  • > Tutorials
  • > PHP cookbook

PHP – convert dos newline to unix format

By admin on Dec 13, 2015

Files or strings in DOS format may have \r (carriage return) along with \n (newline). This may appear as ^M in some editors.
vi-dos-file-showing-ctr-m-in-vi
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

  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.

Suggested posts:

  1. How to do grep without regex (fixed string)
  2. Bash – how to compare file timestamps
  3. How to install Imagemagick on Ubuntu Linux
  4. php cli – find which ini file is loaded
  5. Bash – add a number to a variable
  6. Find authentication methods an ssh server supports
  7. PHP – empty() vs isset() vs is_null() vs boolean check
  8. PHP check if a filename is valid
Share this article: share on facebook share on linkedin tweet this submit to reddit
Posted in Tutorials | Tagged Linux, PHP, PHP cookbook, PHP text processing, Tutorials, Ubuntu Linux
  • Browse content
  • Article Topics
  • Article archives
  • Contact Us
Popular Topics: Android Development | AngularJS | Apache | AWS and EC2 | Bash shell scripting | Chrome developer tools | Company results | CSS | CSS cookbook | CSS properties | CSS Pseudo Classes | CSS selectors | CSS3 | CSS3 flexbox | Devops | Git | HTML | HTML5 | Java | Javascript | Javascript cookbook | Javascript DOM | jQuery | Kubernetes | Linux | Linux/Unix Command Line | Mac | Mac Command Line | Mysql | Networking | Node.js | Online Tools | PHP | PHP cookbook | PHP Regex | Python | Python array | Python cookbook | SEO | Site Performance | SSH | Ubuntu Linux | Web Development | Webmaster | Wordpress | Wordpress customization | Wordpress How To | Wordpress Mysql Queries | InfoHeap Money

Copyright © 2025 InfoHeap.

Powered by WordPress