0

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

Mohan Raj
  • 167
  • 12

2 Answers2

2

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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