简体   繁体   English

preg_match第一个SELECT和最后一个FROM之间的所有内容

[英]preg_match everything between first SELECT and last FROM

I want to have a regular expression that matches everything between the first SELECT and the last FROM in a SQL statement with PHP. 我想要一个正则表达式,该表达式与PHP的SQL语句中的第一个SELECT和最后一个FROM之间的所有内容匹配。 To put this into an example: 举一个例子:

SELECT
    `t1`.`id`,
    `t1`.`created`,
    (
        SELECT
            `t2`.`content`
        FROM
            `table2` `t2`
        WHERE
            `t1`.`id` = `t2`.`id`
    ) `sub`
FROM
    `table1` `t1`

In the statement above statement I want to match: 在上面的语句中,我要匹配:

`t1`.`id`,
    `t1`.`created`,
    (
        SELECT
            `t2`.`content`
        FROM
            `table2` `t2`
        WHERE
            `t1`.`id` = `t2`.`id`
    ) `sub`

I tried doing this myself, but I can't get it working properly. 我尝试自己做,但是无法正常工作。

You can use a basic regular expression to achieve this ... 您可以使用基本的正则表达式来实现这一目标...

preg_match('~SELECT(.*)FROM~si', $text, $match);
echo $match[1];

Code Demo 代码演示

(?<=SELECT\s)(.*)(?=\sFROM)

Try this.Grab the capture.See demo. 试试看,获取捕捉,请看演示。

http://regex101.com/r/rQ6mK9/15 http://regex101.com/r/rQ6mK9/15

Use DOTALL modifier to make dot to match even newline characters also. 使用DOTALL修饰符使点也可以匹配换行符。 \\K in the below regex would discard the previously matched characters from printing. 以下正则表达式中的\\K将从打印中丢弃先前匹配的字符。

(?s)SELECT[^\n]*\n\K.*(?=[^\n]*FROM)

OR 要么

(?s)SELECT[^\n]*\n\K.*(?=\n[^\n]*?FROM)

DEMO DEMO

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

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