3

我有一系列正则表达式,其中包括我需要存储在 mysql 表中的转义字符。

如果我不逃避反斜杠,它就会被淘汰。

我尝试使用 mysql_real_escape_string、addslashes、str_replace 转义 PHP 中的反斜杠,并且每次数据库存储双反斜杠而不是单个反斜杠时。

我也尝试在 bash 中使用 sed 来转义反斜杠,但它也会打印 2。

例子:

$regex = "stackoverflow\.com\/questions\/ask";
$query_text = addslashes($regex);
$query = "INSERT INTO my_table (url) VALUES ('$query_text')";

me@server:$ echo "select * from my_table" | mysql -uuser -Ddatabase -p'password'

stackoverflow\\.com\\/questions\\ask

关于我做错了什么的任何想法?

4

1 回答 1

9

斜杠在 mysql 客户端的控制台输出中被转义;不在数据库中;)

尝试以交互方式运行客户端:

mysql -uuser -Ddatabase -p'password'
mysql> select * from my_table;
+------------------------------------+
| x                                  |
+------------------------------------+
| stackoverflow\.com\/questions\/ask |
+------------------------------------+

并且是非交互的:

mysql -uuser -Ddatabase -p'password' <<< "select * from my_table"
stackoverflow\\.com\\/questions\\/ask

用于--raw禁用此转义:

mysql -uuser -Ddatabase -p'password' --raw <<< "select * from my_table"
stackoverflow\.com\/questions\/ask

从手册:

--原始,-r

For tabular output, the “boxing” around columns enables one column value to be distinguished from another. For nontabular output (such as is produced in batch mode or when the --batch or --silent option is given), special characters are escaped in the output so they can be identified easily. Newline, tab, NUL, and backslash are written as \n, \t, \0, and \. The --raw option disables this character escaping.

BTW mysql_real_escape_string was the right escape function to use.

于 2011-09-02T18:26:26.327 回答