0

Example

$string = "Test Line 1 
Test Line 2 
Test Line 3"; 
echo str_replace(PHP_EOL,"/".PHP_EOL, $string ); 

Actually I am expecting output is

Test Line 1 \

Test Line 2 \

Test Line 3 \

Please help me to solve this problem

Community
  • 1
  • 1
  • 2
    I imagine you're having trouble printing the \ because it's escaping the quote. Try `str_replace(PHP_EOL,"\\".PHP_EOL, $string );` – Ankh Nov 19 '15 at 11:58
  • the php file used is saved with a line ending (say, CRLF) different from the system (osx, *nix) native format (LF), thus replacement doesn't work as expected. check your text editor configuration for that file. – Calimero Nov 19 '15 at 11:58
  • @Ankh It's wrong slash `/` will not escape anything. Also it's not possible output, because in code you use `/` while expecting to get `\\` – Justinas Nov 19 '15 at 11:59
  • 1
    @Justinas That's the example, look at the expected output... – Ankh Nov 19 '15 at 11:59
  • Perhaps you should use a backslash ``\`` instead of a slash`/` if you want to have a backslash in your output? – Stefan Gehrig Nov 19 '15 at 12:00
  • 1
    @Ankh You are right. it will work with your code as expected – Pratik Soni Nov 19 '15 at 12:01
  • @Ankh It does not work. I've tested in phpfiddle.org – Basheer Kharoti Nov 19 '15 at 12:03
  • @Ankh but your code not add \ at the last line – Saty Nov 19 '15 at 12:03
  • This answer should meet your requirements http://stackoverflow.com/questions/128560/when-do-i-use-the-php-constant-php-eol – Basheer Kharoti Nov 19 '15 at 12:08
  • 1
    As `PHP_EOL` is platform-dependent, I think, it's problematic to use if the source of the string is unkown. Say the string uses `\r\n` while your platform uses `\n` only. A regular expression, handling both cases whould be more *safe*. – Yoshi Nov 19 '15 at 12:08

3 Answers3

1

Use \\ instead of "/"

<?php
$string = "Test Line 1 
Test Line 2 
Test Line 3"; 
 $var=str_replace(PHP_EOL,"\\"."</br>", $string ); 
echo $var." \\"; // this append \ in last string
?>
Saty
  • 22,443
  • 7
  • 33
  • 51
  • This is the output you would get from this code, `Test Line 1 \ Test Line 2 \ Test Line 3\\`, and this is not the expected output. – Rajdeep Paul Nov 19 '15 at 12:16
  • @RajdeepPaul check result in browser console it will show you exact output – Saty Nov 19 '15 at 12:19
1

Try this,

Edited:

<?php
    $string = "Test Line 1 
    Test Line 2 
    Test Line 3"; 
    $str = str_replace(PHP_EOL,"\<br />", $string) . " \\"; 
    echo $str;
?>
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
0

If this is just so that you can put the php value into a JS variable, you can just use json_encode() which will change the new lines to \n for you

$string = "Test Line 1 
Test Line 2 
Test Line 3"; 

echo json_encode($string);
// outputs(including quotes) "Test Line 1 \nTest Line 2 \nTest Line 3"