如何获得一个表达式中的括号和逗号内的字符串(正则表达式/ PHP)
问题描述:
我觉得我的问题很容易解决,但我不能。如何获得一个表达式中的括号和逗号内的字符串(正则表达式/ PHP)
我想利用我的查询字符串里面这句话:
$string = "INSERT INTO table (a,b) VALUES ('foo', 'bar')";
预期结果:
array one = [a,b]
array two = [foo, bar]
答
有,你可以根据你如何灵活需要使用这么多的正则表达式策略成为。这里有一个非常简单的实现,它假定你知道字符串'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/(还有很多其他的)
'preg_match()'也许。 – AbraCadaver 2015-03-30 19:35:22
为什么,如果我可能会问? – Nanne 2015-03-30 19:35:50
[preg \ _match for information in brackets]的可能重复(http://stackoverflow.com/questions/6378229/preg-match-for-information-in-parentheses) – 2015-03-30 19:36:40