str_replace is not woking with input

To remove the new line the following code is working good;

<?php 
  $text = "Hello \nwelcome to \ngeeksforgeeks"; 
  $text = str_replace("\n", "", $text); 
 echo $text; 
?>

OUTPUT:Hello welcome to geeksforgeeks.

But when i get it as input it is not working;

 <form method="post">
       <label>enter string</label>&nbsp
       <input type="text" name="string"></input><br><br>
       <input type="submit" name="enter"></input>
 </form>
<?php 
    if(isset($_POST['enter']))
    {
      $text=$_POST['string'];
     $out=str_replace("\n","",$text);
      echo $out;

     }
 ?>

INPUT:Hello \nwelcome to \ngeeksforgeeks;

OUTPUT:Hello \nwelcome to \ngeeksforgeeks.

please tell me the reason

2 answers

  • answered 2020-01-14 01:53 Barmar

    In a double-quoted string, \n is an escape sequence that becomes a newline character. You want to match literal \n in the user input, so you should use a single-quoted string, which doesn't process escape sequences.

    if(isset($_POST['enter']))
    {
        $text=$_POST['string'];
        $out=str_replace('\n',"",$text);
        echo $out;
    }
    

    See What is the difference between single-quoted and double-quoted strings in PHP?

  • answered 2020-01-14 02:47 Wang Zhongwen

    $out=str_replace('\n',"",$text); or $out=str_replace("\\n","",$text);