gpt4 book ai didi

php - 使用 preg_match 查找列表中的所有单词

转载 作者:可可西里 更新时间:2023-11-01 13:31:07 25 4
gpt4 key购买 nike

在 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));

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

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

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

关于php - 使用 preg_match 查找列表中的所有单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6351190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com