1

给定一个字符串,匹配单词第一次出现之后出现的所有内容。该单词不得出现在一对括号内的任何位置,但其他单词可以。例如:

SELECT
t1.col1,
(SELECT t2.col1 FROM table2 t2
    WHERE t2.id IN(SELECT * FROM table5 WHERE id = t2.id)
) AS alias1,
t1.col2
----------
FROM
table1 t1,
(SELECT id FROM table3 t3 WHERE t3.id = t1.table3_id) t3,
table4 t4

我正在寻找虚线之后的所有内容-特别是在单词第一次出现之后FROM没有出现在一对括号内的任何内容之后的所有内容

如果 Regex 不行,我会制作一个 PHP 语句来解析。我也很难过,寿!我想这样做,我必须按单词和括号对字符串进行标记?

4

2 回答 2

1

我认为正则表达式可能不是最好的解决方案,因为当涉及嵌套括号时,它们可能非常困难(或不可能)。

我也认为循环遍历每个字符并不是最好的方法,因为它会导致很多不必要的循环。

我认为这是最好的方法:

查找给定字符串的每次出现并计算出现之前的括号数。如果左括号的数量等于右括号的数量,那么你有正确的匹配。这将导致更少的循环,并且您只是在检查您真正要检查的内容。

我做了一个findWord采用这种方法的函数。它适用于您的示例 where $inis your SQL statement and $searchis 'FROM'.

function findWord( $in, $search ) {

    if( strpos($in, $search) === 0 ) return $in;

    $before = '';
    while( strpos($in, $search, 1) ) {
        $i = strpos($in, $search, 1);
        $before .= substr($in, 0, $i);
        $in = substr($in, $i);

        $count = count_chars($before);

        if( $count[40] == $count[41] )
            return $in;
    }

    return false;
}
于 2013-02-04T06:41:50.377 回答
0

除非有人有更好的答案,否则我将采用程序化方法。

/**
 * Find the portion of the SQL statement occurring after
 * the first occurrence of the word 'FROM' (which itself
 * does not appear within parens)
 */
public static function sql_after_from($sql) {
    $arr = str_split($sql);
    $indent = 0;
    $out = '';
    $start = 0;
    $len = count($arr);
    for($x=0; $x < $len; $x++) {
        $c = $arr[$x]; //current character
        if($c == '(') $indent++;
        if($c == ')') $indent--;
        $out .= $arr[$x];
        //do the last 4 letters spell FROM?
        if(substr($out, $x-3, $x) == 'FROM') {
            if($indent == 0) { //not anywhere within parens
                $start = $x+2;
                break; //go no further 
            }
        }
    }
    //everything after the first occurrence of FROM
    return substr($sql, $start);
}
于 2013-02-04T05:14:21.833 回答