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. PHP remove trailing whitespaces and newline
  2. Bash – newline and other escape character in string
  3. PHP – Regex OR (alternation) examples using pipe
  4. php get array value with default
  5. bash – how to use regex in if condition
  6. Bulk convert jpeg files to png using sips on mac
  7. PHP regex – whitespace shorthand (\s) regex examples
  8. Convert mp3 to ogg on Mac using ffmpeg
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 | 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

Copyright © 2023 InfoHeap.

Powered by WordPress