简体   繁体   中英

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.

From the official docs of PHP on mysqli_real_escape_string :

mysqli_real_escape_string ( mysqli $link , string $escapestr ) : string

escapestr: The string to be escaped.

Characters encoded are NUL (ASCII 0), \\n, \\r, \\, ', ", and Control-Z.

How is it possible to omit the \\n from this list but keeping the others intact?

Solution 1: You can achieve this by:

  • Explode your string to array using \\n .
  • Loop the array and have each item escaped.
  • Put them back using Implode and \\n as glue.

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:

  • Replace \\n with some text (eg # NEWLINE #).
  • Do the string escape.
  • Replace the text from step 1 to \\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); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM