字串與正規表示式匹配

preg_match 檢查字串是否與正規表示式匹配。

$string = 'This is a string which contains numbers: 12345';

$isMatched = preg_match('%^[a-zA-Z]+: [0-9]+$%', $string);
var_dump($isMatched); // bool(true)

如果傳入第三個引數,則會使用正規表示式的匹配資料填充:

preg_match('%^([a-zA-Z]+): ([0-9]+)$%', 'This is a string which contains numbers: 12345', $matches);
// $matches now contains results of the regular expression matches in an array.
echo json_encode($matches); // ["numbers: 12345", "numbers", "12345"]

$matches 包含整個匹配的陣列,然後是括號括起來的正規表示式中的子字串,按左括號的偏移順序排列。這意味著,如果你有/z(a(b))/作為正規表示式,索引 0 包含整個子字串 zab,索引 1 包含由外部括號 ab 限定的子字串,索引 2 包含內部括號 b