php 从php中的字符串转义特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33011956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:19:48  来源:igfitidea点击:

escape special character from string in php

phpmysqlarrays

提问by Gopal

we are trying to escape some special character from our string please tell me the function that we have to use e.g. HTC Desire 210 – White
In this example we escape -(hyphen) special character. In above example we have lot of product name with different different special character that we escape it. thanks for your co-operation.

我们试图从我们的字符串中转义一些特殊字符,请告诉我我们必须使用的函数,例如 HTC Desire 210 – White
在这个例子中我们转义 -(连字符)特殊字符。在上面的例子中,我们有很多具有不同特殊字符的产品名称,我们对其进行了转义。谢谢你的配合。

回答by chandresh_cool

You can use str_replace, for example ;

例如,您可以使用str_replace

str_replace(array(':', '-', '/', '*'), '', $string);

回答by Navnish Bhardwaj

The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.

mysqli_real_escape_string() 函数转义字符串中的特殊字符以用于 SQL 语句。

Syntax:

句法:

mysqli_real_escape_string(connection,escapestring);

ExampleEscape special characters in a string:

示例转义字符串中的特殊字符:

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?> 

connectionRequired. Specifies the MySQL connection to use

连接必需。指定要使用的 MySQL 连接

escapestringRequired. The string to be escaped. Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

转义字符串必需。要转义的字符串。编码的字符为 NUL (ASCII 0)、\n、\r、\、'、" 和 Control-Z。

回答by Nana Partykar

Pass string in this function.

在此函数中传递字符串。

function clean($string) 
{
   $string = str_replace(' ', '-', $string); // Replaces spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

For more info, check this Remove Special Character - Stackoverflow

有关更多信息,请查看此删除特殊字符 - Stackoverflow

回答by David Partyka

If you need to escape characters that would break a regex / PCRE function (e.g., preg_match()) if not escaped, you can use preg_quote()

如果您需要转义会破坏正则表达式 / PCRE 函数的字符(例如,preg_match()),如果没有转义,您可以使用preg_quote()

For example, let's say your needle and haystack are:

例如,假设您的针和干草堆是:

$needle   = "needle(";
$haystack = "ibivfdubdvwbneedle(cihbdhcbds";

The following preg_match()will throw a warning:

以下preg_match()将引发警告:

var_dump(preg_match("/" . $needle . "/", $haystack)); -----> WARNING preg_match(): Compilation failed: missing ) at offset 7 on line number 9 bool(false)

because a left parenthesis is a character used in regular expression syntax. However, if you use preg_quote()on the needle, the left parenthesis will be escaped and the regex check will execute:

因为左括号是正则表达式语法中使用的字符。但是,如果您preg_quote()在针上使用,左括号将被转义,并且正则表达式检查将执行:

var_dump(preg_match("/" . preg_quote($needle) . "/", $haystack)); ----> int(1)

More discussion about preg_quote()here.

关于preg_quote()这里的更多讨论。

回答by Haritsinh Gohil

You can escape special characters in mysqli using function mysqli_real_escape_string().

您可以使用函数mysqli_real_escape_string()在 mysqli 中转义特殊字符。

Syntax:

句法:

mysqli_real_escape_string(connection,escapestring);

mysqli_real_escape_string(connection,escapestring);

Example:

例子:

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$your_string = 'string "hi" ';
$escaped_string = mysqli_real_escape_string($con, $your_string);
$sql = 'select * from tablename where fields like "%'.$escaped_string. '%" ';
$result = $conn->query($sql);

//here you can iterate over result array for displaying result

?>

you can also use addslashes()which Returns a string with backslashes added before characters like:

您还可以使用addslashes()返回一个在字符前添加反斜杠的字符串,例如:

  • single quote (')
  • double quote (")
  • backslash (\)
  • NUL (the NUL byte)
  • 单引号 (')
  • 双引号 (")
  • 反斜杠 (\)
  • NUL(NUL 字节)

But addslashes()has some vulnerabilities to sql injections for detail see the answer of this question Examples of SQL Injections through addslashes(), so better to use mysqli_real_escape_string()function.

但是addslashes()对 sql 注入有一些漏洞,详细信息请参阅此问题的答案通过添加斜线()进行 SQL 注入的示例,因此最好使用mysqli_real_escape_string()函数。

Or if you want to escape characters for regular expressionsthen you can use preg_quote ( string $str [, string $delimiter = NULL ] ), which puts a backslash in front of every character that is part of the regular expressionsyntax. regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

或者,如果您想为正则表达式转义字符,则可以使用 preg_quote ( string $str [, string $delimiter = NULL ] ),它会在作为正则表达式语法一部分的每个字符前放置一个反斜杠。正则表达式字符是:. \ + * ? [ ^ ] $ ( ) { } = ! < > | :-

Note:But be careful preg_quote()will not escape single(')or double quote(").

注意:但要小心preg_quote()不会逃逸single(')double quote(")

回答by Krish

use the system function $city = $mysqli->real_escape_string($city);

使用系统函数 $city = $mysqli->real_escape_string($city);

here : http://php.net/manual/en/mysqli.real-escape-string.php

这里:http: //php.net/manual/en/mysqli.real-escape-string.php