如何在括号中获取表达式,在字符串中获取逗号(regex/PHP)


How to get a expression inside parentheses and commas inside a string (regex/PHP)

我觉得我的问题很容易解决,但我做不到。

我想把这个词放在我的查询字符串中:

$string = "INSERT INTO table (a,b) VALUES ('foo', 'bar')";

预期结果:

array one = [a,b]
array two = [foo, bar]

根据您需要的灵活性,您可以使用许多regex策略。这里有一个非常简单的实现,它假设您知道字符串"VALUES"是全大写的,并且在"VALUES"和两组括号之前和之后只有一个空格。

$string = "INSERT INTO table (a,b) VALUES ('foo', 'bar')";
$matches = array();
// we escape literal parenthesis in the regex, and also add 
// grouping parenthesis to capture the sections we're interested in
preg_match('/'((.*)') VALUES '((.*)')/', $string, $matches);
// make sure the matches you expect to be found are populated
// before referencing their array indices. index 0 is the match of
// our entire regex, indices 1 and 2 are our two sets of parens
if (!empty($matches[1]) && !empty($matches[2]) {
  $column_names = explode(',', $matches[1]); // array of db column names
  $values = explode(',', $matches[2]);  // array of values
  // you still have some clean-up work to do here on the data in those arrays.
  // for instance there may be empty spaces that need to be trimmed from 
  // beginning/ending of some of the strings, and any of the values that were
  // quoted need the quotation marks removed.
}

这只是一个起点,一定要在数据上测试它,并根据需要修改正则表达式!

我建议使用regex测试仪,根据您需要的实际查询字符串来测试您的regex字符串。http://regexpal.com/(还有很多其他)