[英]How to use mysqli_real_escape_string() in PHP to escape all characters except newline?
I have a text input which can contain special chars that needs to be escaped. 我有一个文本输入,其中可以包含需要转义的特殊字符。 But I also want to preserve the newlines. 但是我也想保留换行符。 Using PHP's mysql_real_escape_string(), how is it possible to ignore the newline ('\\n') from escaping. 使用PHP的mysql_real_escape_string(),如何可以避免换行符('\\ n')的转义。
From the official docs of PHP on mysqli_real_escape_string
: 从PHP的官方文档 (关于mysqli_real_escape_string
:
mysqli_real_escape_string ( mysqli $link , string $escapestr ) : string
escapestr: The string to be escaped. escapestr:要转义的字符串。
Characters encoded are NUL (ASCII 0), \\n, \\r, \\, ', ", and Control-Z. 编码的字符为NUL(ASCII 0),\\ n,\\ r,\\,',“和Control-Z。
How is it possible to omit the \\n
from this list but keeping the others intact? 如何从此列表中省略\\n
但保持其他完整无缺?
Solution 1: You can achieve this by: 解决方案1:您可以通过以下方法实现此目的:
\\n
. 使用\\n
将您的字符串分解为数组。 \\n
as glue. 使用Implode和\\n
作为胶水将它们放回去。 Code: 码:
<?php
$array = explode('\n',$stringToEscape);
$index = 0;
foreach($array as $string){
$array[$index] = mysqli_real_escape_string ( $link , $string) ;
$index++;
}
$excapedString = implode('\n',$array);
?>
Solution 2: Another solution: 解决方案2:另一个解决方案:
\\n
with some text (eg # NEWLINE #). 用一些文本替换\\n
(例如# NEWLINE #)。 \\n
. 将步骤1中的文本替换为\\n
。 Code: 码:
<?php
$string = '##YOUR STRING TO BE ESCAPED##';
$stringToEscape = str_replace('\n','#_NEWLINE_#',$string);
$escapedString = mysqli_real_escape_string ( $link , $stringToEscape ) ;
$finalString = str_replace('#_NEWLINE_#','\n',$escapedString);
?>
You can use custom escape function like this one: 您可以像这样使用自定义转义功能:
function my_escape_function($value) { $search = array("\\\\", "\\x00", "\\r", "'", '"', "\\x1a"); $replace = array("\\\\\\\\","\\\\0", "\\\\r", "\\'", '\\"', "\\\\Z"); return str_replace($search, $replace, $value); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.