在字符串中查找INSERT语句的一部分的位置

时间:2013-01-31 04:50:22

标签: php mysql preg-match-all

我试图在INSERT语句中的单词“VALUES”之后找到字符串位置,这将是实际行数据之前的位置。

我知道我需要使用正则表达式来获取INSERT语句的模式,而不是使用strpos来查找单词“VALUES”,但是当涉及到正则表达式函数时,我有点像新手。< / p>

已更新

我想找到“)VALUES的位置(”并允许括号之间的空格,\ n,\ 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');

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

$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)));
}