【问题标题】:Using preg_match to find all words in a list使用 preg_match 查找列表中的所有单词
【发布时间】:2011-06-15 17:50:57
【问题描述】:

在 SO 的帮助下,我能够从电子邮件主题行中提取“关键字”以用作类别。现在我决定允许每张图片有多个类别,但似乎无法正确表达我的问题以获得谷歌的良好回应。 preg_match 在列表中的第一个单词处停止。我确信这与“渴望”或只是将管道符号 | 替换为其他东西有关,但我就是看不到它。
\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b .

我当前使用的整个字符串是:

preg_match("/\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b/i", "." . $subject . ".", $matches);

我需要做的就是将所有这些单词都提取出来(如果它们存在),而不是停留在 amsterdam 或者它正在搜索的主题中出现的任何单词。之后,就是处理$matches数组的事情了,对吧?

谢谢, 标记

【问题讨论】:

  • 尝试preg_match_all - php.net/manual/en/function.preg-match-all.php - 只需将_all 添加到函数名称中。
  • 我还要补充一点,$matchespreg_match_all 略有不同
  • 非常感谢!是的,$matches 确实发生了变化。乍一看,现在似乎是数组中的数组。 print_r($matches) 给了我 Array ( [0] => Array ( [0] => paris [1] => bulle ) ) 。我正在研究它,但有什么明显的建议可以解决这个问题吗?
  • 再次感谢@hakre 和@datasage 的帮助。不知道它是否“正确”,但我让它与嵌套的 foreach 循环一起工作。
  • 马克,我添加了更多示例代码的答案。由于 $matches 中的值发生了变化,只有添加 _all 有点短,因为 datasage 确实正确提及。该示例展示了如何将结果转换为一个简单的城市数组。

标签: php preg-match


【解决方案1】:

好的,这里有一些带有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));

由于$foundCities 现在是一个简单的数组,您也可以直接对其进行迭代:

foreach($foundCities as $index => $city) {
    echo $index, '. : ', $city, "\n";
}

不需要嵌套循环,因为 $matches 返回值已经标准化。这个概念是让代码在您需要时返回/创建数据以进行进一步处理。

【讨论】:

  • 非常感谢您的额外帮助!这对我来说很清楚。我知道有一种适当的方法可以做到这一点。
猜你喜欢
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多