为了删除新行,以下代码运行良好;
<?php
$text = "Hello \nwelcome to \ngeeksforgeeks";
$text = str_replace("\n", "", $text);
echo $text;
?>
输出:您好,欢迎来到geeksforgeeks。
但是当我得到它作为输入时,它不起作用;
<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:您好,\ n欢迎来到\ ngeeksforgeeks;
输出:您好\欢迎来到\ ngeeksforgeeks。
请告诉我原因
在双引号字符串中,\n
是转义序列,成为换行符。您要在用户输入中匹配文字\n
,因此应使用单引号字符串,该字符串不处理转义序列。
if(isset($_POST['enter']))
{
$text=$_POST['string'];
$out=str_replace('\n',"",$text);
echo $out;
}
请参见What is the difference between single-quoted and double-quoted strings in PHP?
$ out = str_replace('\ n',“”,$ text);要么$ out = str_replace(“ \\ n”,“”,$ text);