2015-03-30 119 views
0

我覺得我的問題很容易解決,但我不能。如何獲得一個表達式中的括號和逗號內的字符串(正則表達式/ PHP)

我想利用我的查詢字符串裏面這句話:

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

預期結果:

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

'preg_match()'也許。 – AbraCadaver 2015-03-30 19:35:22

+2

爲什麼,如果我可能會問? – Nanne 2015-03-30 19:35:50

+0

[preg \ _match for information in brackets]的可能重複(http://stackoverflow.com/questions/6378229/preg-match-for-information-in-parentheses) – 2015-03-30 19:36:40

回答

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/(還有很多其他的)