在SO的帮助下,我能够从电子邮件主题行中提取"关键字"以用作类别.现在我决定允许每个图像使用多个类别,但似乎无法正确地说出我的问题以获得Google的良好回应.preg_match停在列表中的第一个单词.我确信这与"渴望"或仅仅用|其他东西替换管道符号有关,但我无法看到它.
\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b.
我目前使用的整个字符串是:
preg_match("/\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b/i", "." . $subject . ".", $matches);
我需要做的就是把所有这些话都拿出去,而不是停在阿姆斯特丹,或者在它正在搜索的主题中首先出现的话.在那之后,这只是处理$ matches数组的问题,对吧?
谢谢,马克
好的,这里有一些示例代码,preg_match_all()展示了如何删除嵌套:
$pattern = '\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b';
$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.\n", count($foundCitites), implode('; ', $foundCities));
Run Code Online (Sandbox Code Playgroud)
现在是$foundCities一个简单的数组,您也可以直接迭代它:
foreach($foundCities as $index => $city) {
echo $index, '. : ', $city, "\n";
}
Run Code Online (Sandbox Code Playgroud)
不需要嵌套循环,因为$matches返回值已经标准化。这个概念是让代码根据需要返回/创建数据以进行进一步处理。