PHP 字符串与正则表达式匹配

示例

preg_match 检查字符串是否与正则表达式匹配。

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

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

如果您传入第三个参数,它将使用正则表达式的匹配数据填充:

preg_match('%^([a-zA-Z]+): ([0-9]+)$%', 'This is a string which contains numbers: 12345', $matches);
// $matches现在包含数组中正则表达式匹配的结果。
echo json_encode($matches); // ["numbers: 12345", "numbers", "12345"]

$matches包含整个匹配项的数组,然后是包含在括号中的正则表达式中的子字符串,其子字符串的开头是括号的偏移量。这意味着,如果您有正则表达式,则索引0包含整个子字符串,索引1包含由外部括号界定的子字符串,而索引2包含内部括号。/z(a(b))/zababb