Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Removing Windows ^M Character

I have a CSV I am downloading from a source I'm not in control of and the end of each line is a

^M 

character when printed to a bash terminal. How can I sanitize this input programmatically in PHP?

like image 780
nsfyn55 Avatar asked Aug 07 '12 19:08

nsfyn55


People also ask

What is Ctrl M character?

It is known as carriage return. If you're using vim you can enter insert mode and type CTRL - v CTRL - m . That ^M is the keyboard equivalent to \r.

What is the M character?

M is a codename held by a number of fictional characters in Ian Fleming's James Bond book and film series; the characters are the current or past heads of the Secret Intelligence Service—also known as MI6. Fleming based the character on a number of people he knew who commanded sections of British intelligence.

Why m in Linux?

Control M ( ^M) characters are introduced when you use lines of text from a windows computer to Linux or Unix machine. Most common reasons are when you directly copy a file from a windows system or submit form data copied and pasted from a windows machine.


2 Answers

What you're seeing is a Windows control character. To get rid of this in PHP, what you need to do is $file = str_ireplace("\x0D", "", $file) this will work whether hexadecimal is lowercase or uppercase.

like image 115
jarriett Avatar answered Oct 06 '22 18:10

jarriett


You can also ask PHP to auto detect any weird line endings by just adding in this line before reading the CSV file and you won't be required to do anything else.

ini_set('auto_detect_line_endings', true);
like image 45
Kamal Soni Avatar answered Oct 06 '22 17:10

Kamal Soni