InfoHeap
Tech tutorials, tips, tools and more
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.3.18 (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. Imagemagick – how to create animation on command line
  2. How to install Imagemagick on Ubuntu Linux
  3. How to create animated gif using Mac preview
  4. Bulk convert jpeg files to png using sips on mac
  5. PHP remove trailing whitespaces and newline
  6. Bash – newline and other escape character in string
  7. Linux – Yesterday’s Date in YYYYMMDD format
  8. Linux/Unix – How to go to previous directory
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

Follow InfoHeap

facebook
twitter
googleplus
  • Browse site
  • Article Topics
  • Article archives
  • Recent Articles
  • Contact Us
  • Omoney
Popular Topics: AngularJS | Apache | AWS and EC2 | Bash shell scripting | Chrome developer tools | CSS | CSS cookbook | CSS properties | CSS Pseudo Classes | CSS selectors | CSS3 | CSS3 flexbox | Devops | Git | HTML | HTML5 | Java | Javascript | Javascript cookbook | Javascript DOM | jQuery | 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

Copyright © 2022 InfoHeap.

Powered by WordPress