我正在尝试在 INSERT 语句中查找单词"VALUES"之后的字符串位置,这将是实际行数据之前的位置。
我知道我需要使用正则表达式来获取 INSERT 语句的模式,而不是使用 strpos 来查找"VALUES"这个词,但是当涉及到正则表达式函数时,我有点新手。
更新
我想找到") 的位置值 (" 并允许括号之间的空格、'、''r、''t 等,因为有时 VALUES 位于新行上。
谢谢
SQL文件:
# ------------------------------
# --
# -- Dumping data for table `table_a`
# --
INSERT INTO `table_a` (`a`, `b`, `c`, `d`)
VALUES -- get position
(1, 'b', 'c', 'd'),
(2, 'b', 'c', 'd'),
(3, 'b', 'c', 'd');
# ------------------------------
# --
# -- Dumping data for table `table_b`
# --
INSERT INTO `table_b` (`a`, `b`, `c`, `d`) VALUES -- get position
(1, 'b', 'c', 'd'),
(2, 'b', 'c', 'd'),
(3, 'b', 'c', 'd');
这应该可以解决问题:
$content = file_get_contents('/path/to/dump.sql');
$pattern = '/')'s+VALUES's+'(/U';
$matches = array();
$match_count = preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE);
// trim off the parenthesis and whitespace from each match and add length of remaining portion of match string to the match offset to get offset at end of 'VALUES'
$offsets = array();
foreach($matches[0] as $match) {
$offsets[] = $match[1] + strlen(rtrim(substr($match[0], 0, -1)));
}