使用preg_match查找列表中的所有单词 [英] Using preg_match to find all words in a list

查看:30
本文介绍了使用preg_match查找列表中的所有单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我所需要做的就是取出所有这些单词,如果它们存在的话,而不是停留在阿姆斯特丹,或者它搜索的主题中首先出现的任何单词。在此之后,只需处理$Matches数组,对吗?

谢谢, 标记

推荐答案

好的,这里有一些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返回值已经标准化。其概念是让代码在您需要进一步处理时返回/创建数据。

这篇关于使用preg_match查找列表中的所有单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆