我一直在研究這個半小時,但仍然無法弄清楚。我相信這很簡單。
我想匹配一個ID,但前提是前面有「ID:」。
<?php
$string1 = "Payment: 1474";
$string2 = "Payment ID: 1474";
preg_match('/ID: ([0-9]){1,7}$/', $string1, $matches);
//array(0){} Good! This is the expected result.
preg_match('/ID: ([0-9]){1,7}$/', $string2, $matches);
//array(2) { [0]=> string(8) "ID: 1474" [1]=> string(1) "4" }
//I am glad it finds a match, but I want matches[0] to be only the id, 1474
?>
換句話說,我需要找到一個匹配,但我也需要指定進入數組的內容。
由於我無法學習這一點,如果您不只是回答代碼,而且還要解釋它的作用,我將不勝感激。謝謝!
您需要將重複計數放在括號內。 – Barmar 2013-03-14 01:12:50
請注意,它將在'$ matches [1]'中,而不是'$ matches [0]'中。 – 2013-03-14 01:15:59
爲了擴展@DavidKiger所說的內容,它不會出現在'$ matches [0]'中,因爲它匹配整個['preg_match'](http://www.php.net/manual/en/function.preg- match.php)字符串。 – Jon 2013-03-14 01:21:00