简体   繁体   English

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

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

I think my question is so easy to be solved, but I can't. 我认为我的问题很容易解决,但我不能。

I want to take this words inside of my query string: 我想把这些词放在我的查询字符串中:

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

Expected result: 预期结果:

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

There are many regex strategies you could use for this depending on how flexible you need it to be. 您可以使用多种正则表达式策略,具体取决于您需要的灵活性。 Here is one very simple implementation which assumes that you know the string 'VALUES' is in all caps, and there is exactly one space before and after 'VALUES' and the two sets of parenthesis. 这是一个非常简单的实现,它假定您知道字符串'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.
}

This is only a starting point, be sure to test it on your data and revise the regex as needed! 这只是一个起点,请确保对您的数据进行测试并根据需要修改正则表达式!

I recommend using a regex tester to test your regex string against actual query strings you need it to work on. 我建议使用一个正则表达式测试器,以针对需要使用它的实际查询字符串来测试您的正则表达式字符串。 http://regexpal.com/ (There are many others) http://regexpal.com/ (还有很多其他)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM