更新时间:2022-04-12 17:10:14
好的,这里有一些preg_match_all()
的示例代码,它展示了如何删除嵌套:
$pattern = '(?:amsterdam|paris|zurich|munich|frankfurt|bulle)';
$result = preg_match_all($pattern, $subject, $matches);
# Check for errors in the pattern
if (false === $result) {
throw new Exception(sprintf('Regular Expression failed: %s.', $pattern));
}
# Get the result, for your pattern that's the first element of $matches
$foundCities = $result ? $matches[0] : array();
printf("Found %d city/cities: %s.
", count($foundCitites), implode('; ', $foundCities));
由于$foundCities
现在是一个简单的数组,您也可以直接迭代它:
foreach($foundCities as $index => $city) {
echo $index, '. : ', $city, "
";
}
不需要嵌套循环,因为$matches
返回值已经标准化。其概念是让代码在您需要进一步处理时返回/创建数据。