正则表达式在PHP SQL字符串语句中捕获插入的变量

时间:2016-05-08 09:30:57

标签: php python regex

我有一些正则表达式的麻烦,如果重要的话,使用Python 2.7。

基本上我要做的是在PHP SQL查询字符串声明中捕获插入的变量,例如:

$query  = "SELECT * FROM `users` WHERE user='$user' AND password='$pass';";

当我从比赛中获得第二组时,这应该返回$user

现在这是我的正则表达式:

r'.*?\s*=\s*\(\".*?\'(\$[^\']+)\'.*?\"\);'

Example showing that this works and captures $user but not the one above (yes I know it doesn't capture $pass as it ideally should, that's seems to be a limitation with Python's implementation and Regex in general. I do some hacks to get around this in my actual program)

以上适用于我使用的示例。但是,当我介绍插入变量使用语法'{$foo['bar']}'的另一种情况时,我下面的其他正则表达不起作用,因为它包含一个不关闭变量的撇号:

r'.*?\s*=\s*[\(]?\".*?(?:(?:\'(\$[^\']+)\')|(?:\'(\$\{[^\}]+\})\'))?.*?\"[\)]?;'

所以基本上我想要捕获'$user'语法或带{}的语法,例如'{$foo['bar']}'。请注意,这些并不是唯一的,只是插入的变量可能是任何一种,我想同时考虑这两种变体。

Here's a link to test this out, showing that it doesn't work. Using the second regex also breaks capturing the simple $user, not sure why.

1 个答案:

答案 0 :(得分:1)

我不确定你在python中的限制是什么意思,因为以下工作应该是:

>>> import re
>>> query = "SELECT * FROM `users` WHERE user='$user' AND password='$pass';";
>>> re.findall(r"='(\$\w+)'", query)
['$user', '$pass']

要匹配其他查询,请查看此regex demo

='(\{?\$.+?)(?:'(?:\s|;))

并且,代码示例:

>>> query1 = "(\"SELECT table_schema, table_name, create_time FROM information_schema.tables WHERE table_schema='{$_DVWA['db_database']}' AND table_name='users' LIMIT 1\");"
>>> re.findall(r"='(\{?\$.+?)(?:'(?:\s|;))", query1)
["{$_DVWA['db_database']}"]

# it works on the other query as well
>>> re.findall(r"='(\{?\$.+?)(?:'(?:\s|;))", query)
['$user', '$pass']