简体   繁体   English

PHP正则表达式子字符串

[英]PHP Regular Expression Substring

I have a very long query with a lot of sub-queries in it (almost a thousand lines long). 我有一个很长的查询,里面有很多子查询(差不多一千行)。

What I want to do is to get the names of all the tables that are being used in the query. 我要做的是获取查询中正在使用的所有表的名称。 So take the following example of a query just to get an idea: 因此,以下面的查询示例为例:

SQL Query SQL查询

$sql = "SELECT
    ...,
    ...,
    (
        SELECT COUNT(t.id) AS t_count
        FROM _user_just_a_table_db_ jat
        WHERE ...
        AND ...
        AND ...
    ),
    ...,
    ...,
    ...
    FROM _user_main_table_db_ tbl
    LEFT JOIN _user_joining_table_db_ jt
    ON jt.id = tbl.jt_id
    WHERE ...
    AND ...
    AND tbl.id IN (
        SELECT at.id
        FROM _user_another_table_db_ at
        WHERE at.active = 'Y'
    )";

In this particular situation, I want to get maybe an array or a string with the following results: 在这种特殊情况下,我想获取可能具有以下结果的arraystring

just_a_table
main_table
joining_table
another_table

Notes 笔记

  1. Please note that the names of the table can appear multiple times. 请注意,表名可以出现多次。 You may or may not worry about that as I can easily remove duplicates after getting the resulting array or string . 可能会担心, 也可能不会担心,因为在得到结果arraystring后,我可以轻松删除重复项。
  2. As you may have already noticed, the list of strings that I want to get will ALWAYS be in between _user_ and _db_ . 您可能已经注意到,我想要获取的字符串列表始终_user__db_之间。

This should work 这应该工作

_user_(.*?)_db_

Regex Demo 正则表达式演示

PHP code PHP代码

$match = array();
$re = "/_user_(.*?)_db_/"; 
$str = "SELECT\n    ...,\n    ...,\n    (\n        SELECT COUNT(t.id) AS t_count\n        FROM _user_just_a_table_db_ jat\n        WHERE ...\n        AND ...\n        AND ...\n    ),\n    ...,\n    ...,\n    ...\n    FROM _user_main_table_db_ tbl\n    LEFT JOIN _user_joining_table_db_ jt\n    ON jt.id = tbl.jt_id\n    WHERE ...\n    AND ...\n    AND tbl.id IN (\n        SELECT at.id\n        FROM _user_another_table_db_ at\n        WHERE at.active = 'Y'\n    )\""; 

$res = preg_match_all($re, $str, $match);
print_r($match[1]);

Ideone Demo Ideone演示

$pattern = '/_user_(.*)_db_/';
preg_match_all($pattern, $sql, $match);
var_dump($match[0]);

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

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