php preg_match_all查找空匹配项

时间:2018-10-12 09:45:57

标签: php regex

在网上搜索几个小时后,我遇到了我不明白的错误。 我有一个用POST方法通过ajax查询发出的SQL请求,并且是针对我网站的不同页面生成的,甚至有时是直接由用户输入的。

为避免SQL注入,我想检查参数的内容。 我不能使用PDO :: quote(),因为某些参数可以包含列表或SQL函数:例如:select参数可以包含c.id_client, c.nom, COUNT(c.id_client)...

为防止SQL注入,我将一些SQL关键字和函数与preg_match_all();

列入了黑名单。
$matches = array();
preg_match_all('"[\w% ]*(add|alter|create|delete|drop|exec|insert|set|table|truncate|update|view)[\w% ]*"[^:]', $inputs, $matches);

在我正在测试的情况下,$inputs是json_encoded帖子数组:

{"select":"c.id_client, c.prenom, c.nom, c.email, COUNT(t.actif) AS nombre_licences","from":"clients","as":"c","inner":{"1":{"cond":{"1":{"join_in":"cl.id_client","join_out":"c.id_client"}},"table":"clients_licences","as":"cl"},"2":{"cond":{"1":{"join_in":"t.id_client_licence","join_out":"cl.id_client_licence"},"2":{"join_in":"t.actif","join_out":"1"}},"table":"terminaux","as":"t"}},"where":{"1":{"index":"CONCAT_WS('', c.prenom, c.nom, c.email, c.siren)","operand":"LIKE","value":"%necas%"}},"group":{"1":{"index":"c.id_client"}},"order":{"1":{"index":"c.nom"},"2":{"index":"c.id_client"}},"offset":"0","limit":"3","resultFormat":"<tr class=\"result\"><td>$$id_client##<\/td><td>$$nom## $$prenom##<\/td><td>$$email##<\/td><td>$$nombre_licences##<\/td><td><button class=\"btn btn-xs btn-success\" onclick=\"location.href='\/admin\/view\/$$id_client##'\" ><i class=\"fa fa-search\" aria-hidden=\"true\"><\/i> Voir<\/button><\/td><\/tr>"}

然后我得到:

$matches = [[], []]

我在regex101等不同的正则表达式测试器上测试了几次,但没有任何匹配...

请注意,我不能过多地修改此代码。

感谢您的帮助,Jm56Z

_

编辑:

好像preg_match_all()将$matches设置为包含两倍matchs数组的数组:

$matches = [[matches], [matches]]

2 个答案:

答案 0 :(得分:1)

解决方案:

preg_match_all()将所有匹配项放入多维数组中,即使找不到匹配项也是如此。 默认情况下:

[[matches of the full regex], [matches of group 1], [matches of group 2]...]

下一次,我将更加关注阅读文档。
https://php.net/manual/fr/function.preg-match-all.php

答案 1 :(得分:0)

似乎正则表达式本身是错误的。对于给定的JSON示例,请尝试:

"(add|alter|create|delete|drop|exec|insert|set|table|truncate|update|view)[\w% ]*":