我有這樣的代碼:如何更正preg_match_all正則表達式中子模式的結果?
$query = 'CREATE table "msg" ("myid" INT(10) UNSIGNED , "user" INT(10) UNSIGNED , "new_mes" SMALLINT(5) UNSIGNED , "total_mes" MEDIUMINT(8) UNSIGNED , "lastdate" DATETIME , PRIMARY KEY ("ids"), KEY ("lastdate"))';
我試圖讓主鍵和鍵使用此subpaterns:
preg_match_all('/(?:\WPRIMARY\W*KEY\W?\()(?P<PRIMARY_KEY>[^)]+)|'.
'(?:\W*KEY\W?\()(?P<KEY>[^)]+)/i',$query,$results);
$primary_key = isset($results['PRIMARY_KEY'][0]) ? $results['PRIMARY_KEY'][0] : '';
$key = isset($results['KEY'][0]) ? $results['KEY'][0] : '';
print_r($results);
我得到這樣的輸出:
Array
(
[0] => Array
(
[0] => PRIMARY KEY ("ids"
[1] =>),KEY ("lastdate"
)
[PRIMARY_KEY] => Array
(
[0] => "ids"
[1] =>
)
[1] => Array
(
[0] => "ids"
[1] =>
)
[KEY] => Array
(
[0] =>
[1] => "lastdate"
)
[2] => Array
(
[0] =>
[1] => "lastdate"
)
)
我找的用雙引號括起來的單詞。結果幾乎可以找到,但我更願意在第一個索引[0]中獲取兩個單詞「ids」和「lastdate」。你能解釋爲什麼它發生在第一個索引中的第一個詞被放置,而第二個索引被放置在第二個索引中?爲什麼在第二和第一個索引中有空字符串。
有沒有辦法如何讓兩個詞在索引0?只是爲了簡化代碼。
你是否需要所有的命名捕獲組?您可以使用['(?| \ WPRIMARY \ W * KEY \ W?\(([^)] +)| \ W * KEY \ W?\(([^)] +))'](https: //regex101.com/r/kG6nE6/1)。請參閱[本演示](http://ideone.com/sBLOYZ)。 –
我知道我不需要他們。我創造它們只是爲了說清楚。 –