gpt4 book ai didi

mysql - 匹配 MySQL 注释的正则表达式

转载 作者:行者123 更新时间:2023-11-29 03:58:19 25 4
gpt4 key购买 nike

我需要从 MySQL 查询中查找并删除所有评论。我遇到的问题是避免使用引号或反引号内的注释标记(--、#、/* ... */)。

最佳答案

在 PHP 中,我使用这段代码取消对 SQL 的注释:

$sqlComments = '@(([\'"`]).*?[^\\\]\2)|((?:\#|--).*?$|/\*(?:[^/*]|/(?!\*)|\*(?!/)|(?R))*\*\/)\s*|(?<=;)\s+@ms';
/* Commented version
$sqlComments = '@
(([\'"`]).*?[^\\\]\2) # $1 : Skip single & double quoted + backticked 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 );

关于mysql - 匹配 MySQL 注释的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7100127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com