字符串与正则表达式匹配

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