PHP实现SQL文件关键词间内容批量提取问题求助
问题:批量提取SQL文件中多组匹配内容
需求
- 打开指定SQL文件
- 找到包含起始关键词
:begin(支持大小写变体、冒号后可带空格)的行并显示该行 - 持续输出后续行直至遇到结束关键词
sqlexception(不区分大小写) - 重复上述操作直至文件末尾
现有问题
提供的PHP代码仅能提取第一组匹配内容,无法循环处理所有符合条件的段落:
$filename = 'test.sql'; $startWord = ':begin'; $endWord = 'sqlexception'; // Open the SQL file for reading $file = fopen($filename, 'r'); if ($file) { $foundStart = false; while (!feof($file)) { $line = fgets($file); if ($foundStart || stripos($line, $startWord) !== false) { $foundStart = true; echo $line; // Display the current line if (stripos($line, $endWord) !== false) { $foundStart = false; // Stop displaying lines after finding the end word } } } fclose($file); } else { echo "Unable to open the file."; }
目标SQL文件内容
getDataNlp:begin declare continue handler for sqlexception begin set returnCode = -1; set returnMsg = 'SQL Exception'; end; if useTransaction = 1 then start transaction; end if; set returnMsg = ''; set returnCode = 0; set @count = 0; set @orgName = orgName; set @orgId = ''; set @oprEmail = oprEmail; CreateOpr:BEGIN DECLARE idx INT DEFAULT 1; DECLARE v_orgName VARCHAR(128) DEFAULT ''; declare continue handler for sqlexception begin set returnCode = -1; set returnMsg = 'SQL Exception'; end; start transaction; set returnCode = 0; set returnMsg = ''; set @count = 0; set @oprName = oprName; select count(1) into @count from Opr where name = @oprName; if (@count > 0) then set returnCode = -1; set returnMsg = 'Opr with same oprName already exist'; rollback; leave CreateOpr; end if; END ;;
期望输出
getDataNlp:begin declare continue handler for sqlexception CreateOpr:BEGIN declare continue handler for sqlexception
解决方案
修复代码
$filename = 'test.sql'; // 正则匹配:后可跟任意空白字符,再匹配begin(不区分大小写) $startPattern = '/:[\s]*begin/i'; $endWord = 'sqlexception'; $file = fopen($filename, 'r'); if ($file) { $foundStart = false; while (!feof($file)) { $line = fgets($file); // 未处于输出状态时,检查是否触发起始条件 if (!$foundStart && preg_match($startPattern, $line)) { $foundStart = true; } // 处于输出状态则打印当前行 if ($foundStart) { echo $line; // 检查是否遇到结束关键词,重置状态 if (stripos($line, $endWord) !== false) { $foundStart = false; } } } fclose($file); } else { echo "Unable to open the file."; }
修复说明
- 起始匹配逻辑优化:将原精确字符串匹配改为正则表达式
/:[\s]*begin/i,支持匹配:begin、:BEGIN、: begin等多种格式,确保不会遗漏大小写或带空格的起始行。 - 状态管理拆分:把状态触发和输出逻辑拆分,避免原代码中
||判断导致的状态混淆,确保每次结束后能正确重置状态,触发下一组匹配。 - 保持不区分大小写:结束关键词仍使用
stripos进行不区分大小写查找,适配SQL中不同大小写的写法。
内容的提问来源于stack exchange,提问作者codename_zoe
相关产品推荐
相关产品推荐

