Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace carriage return

Tags:

php

I have a variable ($myClass[0]->comment;) that has carriage return in it. I want to replace all the carriage return in that variable with "\n" how can I do that.
below may help a bit

$myClass[0]->comment;    

Here is some output

<?php  
          $test = explode(chr(13),$myClass[0]->comment );  
          var_dump($test);  

?> 

OUTPUT

array  
  0 => string '12' (length=2)  
  1 => string '  
' (length=1)   
  2 => string '  
22' (length=3)  

All I want is \n instead of carriage return.

like image 991
Asim Zaidi Avatar asked Jun 28 '10 20:06

Asim Zaidi


3 Answers

If you want to replace each CR (\r) with LF (\n), do this

$str=str_replace("\r", "\n", $str);

If you want a literal \n, do this

$str=str_replace("\r", "\\n", $str);

It's more likely you want to replace CR LF, in which simply search for "\r\n" instead.

like image 76
Paul Dixon Avatar answered Oct 17 '22 01:10

Paul Dixon


preg_replace('/\r\n?/', "\n", $str);

This converts both Windows and Mac line endings to Unix line endings.

like image 25
Artefacto Avatar answered Oct 17 '22 02:10

Artefacto


You can use str_replace() to do this:

$test = str_replace("\r", "\n", $myClass[0]->comment);
like image 20
Daniel Egeberg Avatar answered Oct 17 '22 00:10

Daniel Egeberg