Regular expression to remove comments from SQL statement

后端 未结 8 1784
时光说笑
时光说笑 2020-12-15 12:51

I\'m trying to come up with a regular expression to remove comments from an SQL statement.

This regex almost works:

(/\\*([^*]|[\\r\\n]|(\\*+([^*/]|         


        
8条回答
  •  半阙折子戏
    2020-12-15 13:16

    In PHP, i'm using this code to uncomment SQL:

    $sqlComments = '@(([\'"]).*?[^\\\]\2)|((?:\#|--).*?$|/\*(?:[^/*]|/(?!\*)|\*(?!/)|(?R))*\*\/)\s*|(?<=;)\s+@ms';
    /* Commented version
    $sqlComments = '@
        (([\'"]).*?[^\\\]\2) # $1 : Skip single & double quoted expressions
        |(                   # $3 : Match comments
            (?:\#|--).*?$    # - Single line comments
            |                # - Multi line (nested) comments
             /\*             #   . comment open marker
                (?: [^/*]    #   . non comment-marker characters
                    |/(?!\*) #   . ! not a comment open
                    |\*(?!/) #   . ! not a comment close
                    |(?R)    #   . recursive case
                )*           #   . repeat eventually
            \*\/             #   . comment close marker
        )\s*                 # Trim after comments
        |(?<=;)\s+           # Trim after semi-colon
        @msx';
    */
    $uncommentedSQL = trim( preg_replace( $sqlComments, '$1', $sql ) );
    preg_match_all( $sqlComments, $sql, $comments );
    $extractedComments = array_filter( $comments[ 3 ] );
    var_dump( $uncommentedSQL, $extractedComments );
    

提交回复
热议问题