我正在创建一个程序,该程序应该从用户那里获取代码输入,并将其与其他一些示例代码相匹配,一旦完成,它将打印用户输入代码。我遇到问题的部分是当我打印用户代码时,所有内容都打印出来,而不是缩进和换行符,这是打印出来的:
<!DOCTYPE html>\r\n <script src=\"https://code.jquery.com/jquery-3.0.0.min.js\" integrity=\"sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=\" crossorigin=\"anonymous\"></script>\r\n<html>\r\n <head>\r\n <meta charset=\"utf-8\" />\r\n <title>CodeType</title>\r\n </head>\r\n <body>
而这是输入(以及我想要的最终结果):
<!DOCTYPE html>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<html>
<head>
<meta charset="utf-8" />
<title>CodeType</title>
</head>
<body>
这是我的代码:
<?php include "database.php"; ?>
<?php
if(isset($_POST['submit'])){
$title = mysqli_real_escape_string($con, $_POST['title']);
$code = mysqli_real_escape_string($con, $_POST['code']);
$samplecode = mysqli_real_escape_string($con, $_POST['samplecode']);
$query = "INSERT INTO `assignments` (`title`, `code`) VALUES ('$title', '$code')";
$cleanCode = str_replace( "\r\n", "<br/>" , htmlentities($code));
if(mysqli_query($con, $query)){
if($code = $samplecode){
echo $cleanCode;
}
} else {
echo "fails";
}
}
?>
<body>
<br/>
<form method = "post" action = "">
<label id = "title">Title</label>
<br/>
<input type="text" class="txtInput" name = "title"/>
<br/>
<br/>
<label id = "stuff">Code</label>
<br/>
<textarea placeholder="Type your code in here" name = "code"></textarea>
<br/>
<br/>
<br/>
<label id = "samplecode">Sample testing</label>
<br/>
<textarea placeholder="Type your test code in here" name = "samplecode"></textarea>
<br/>
<input type="submit" name = "submit" value="Submit"/>
<pre><?php echo $cleanCode ?></pre>
</form>
</body>
<script>
$(document).ready(function(){
$('.txtInput').bind("paste",function(e) {
e.preventDefault();
});
$( "button" ).on( "click", function(){
if($(#txtInput).text() == $(#code).text()){
alert("Working");
} else {
alert("Failure");
}
});
});
</script>
</html>
有什么想法吗?
答案 0 :(得分:0)
背景信息:
和C一样,PHP 大概是(说那样,因为我还没有找到它的参考...)将\r\n
/ \n
转换为只是\n
(不同的序列用于换行符取决于the OS.)
mysqli_real_escape_string()
escapes \r
and \n
, among others。
这意味着什么:
我们无需替换\r\n
;相反,我们应该替换\n
。
由于mysqli_real_escape_string()
会转义我们的换行符,因此我们需要将$_POST['code'];
用于与数据库无关的任何内容。
<强> TL; DR 强>
$cleanCode = str_replace( "\r\n", "<br/>" , htmlentities($code));
应该是:
$cleanCode = str_replace( "\n", "<br/>" , htmlentities($_POST['code']));