tags:

views:

59

answers:

6

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.

+5  A: 

You can use str_replace() to do this:

$test = str_replace("\r", "\n", $myClass[0]->comment);
Daniel Egeberg
A: 

you can use str_replace

http://us.php.net/str_replace

str_replace("\r", "\n", $text);

if you first wan't to clear out compound \r\n, so you don't get \n\n you could do

str_replace("\r\n", "\n", $text);
str_replace("\r", "\n", $text);
Zak
+2  A: 

No you don't. You want this:

str_replace("\r\n", "\n", $myClass[0]->comment)
Ignacio Vazquez-Abrams
A: 

Simply use str_replace.

str_replace( "\r", "\n", $string );
Jon Wayne Parrott
+1  A: 

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.

Paul Dixon
+2  A: 
preg_replace('/\r\n?/', "\n", $str);

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

Artefacto