简体   繁体   English

PHP:使用REGEX从任何查询中获取表名(选择,更新,插入,删除)

[英]PHP: using REGEX to get the table name from a any query ( select ,update,insert,delete )

Consider these three sql statements: 考虑这三个sql语句:

SELECT * FROM Users;

DELETE FROM Users WHERE id =1;

UPDATE Users SET name='test' WHERE id= 1;

Now im not very good at REGEX, but i want to get the table name from the postgres query. 现在我不是很擅长REGEX,但我想从postgres查询中获取表名。 Could someone possibly create one for me with a little explanation. 有人可能会为我创建一个有一点解释。

Thanks, 谢谢,

For those simple queries, the following will suffice. 对于那些简单的查询,以下就足够了。 However, note that it will not work when there are subqueries, or UPDATE statements do not start with the word UPDATE (such as cases when there are comments in the header, or the UPDATE is a part of a CTE). 但是,请注意,当存在子查询时它不起作用,或者UPDATE语句不以单词UPDATE开头(例如标题中有注释,或者UPDATE是CTE的一部分)。

WITH stmts(_sql) AS (values ('SELECT * FROM Users1;'::text), ('DELETE FROM Users2 WHERE id =1;'), ('UPDATE Users3 SET name=''test'' WHERE id= 1;'))
SELECT _sql, (regexp_matches(_sql, CASE WHEN _sql ~* '^\s*update' THEN '^\s*update' ELSE 'from' END||'\s+([^\s;]+)', 'im'))[1]
FROM stmts

Tablename is obtained from either what follows to UPDATE as a first statement, or immediately after the first FROM statement. Tablename从UPDATE后面的内容中获取,作为第一个语句,或者紧接在第一个FROM语句之后。 Matches are case insensitive (i) and multiline (m). 匹配不区分大小写(i)和多行(m)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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