如何在字符串内的括号和逗号内获取表达式(regex / PHP)

时间:2015-03-30 19:32:26

标签: php regex

我认为我的问题很容易解决,但我无法解决。

我想在查询字符串中使用这个词:

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

预期结果:

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

1 个答案:

答案 0 :(得分:0)

您可以使用许多正则表达式策略,具体取决于您需要它的灵活性。这是一个非常简单的实现,假设您知道字符串'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.
}

这只是一个起点,请务必根据您的数据进行测试并根据需要修改正则表达式!

我建议使用正则表达式测试程序根据您需要它处理的实际查询字符串来测试您的正则表达式字符串。 http://regexpal.com/(还有很多其他人)