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> 
<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 and the fix.
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?