Using preg_match to find all words in a list

☆樱花仙子☆ 提交于 2019-12-10 13:49:13

问题


With help from SO, I was able to pull a 'keyword' out of an email subject line to use as a category. Now I've decided to allow multiple categories per image, but can't seem to word my question properly to get a good response from Google. preg_match stops at the first word in the list. I'm sure this has something to do with being 'eager' or simply replacing the pipe symbol | with something else, but I just can't see it.
\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b .

The whole string I'm currently using is:

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

All I need to do is pull all of these words out if they are present, as opposed to stopping at amsterdam, or whatever word comes first in the subject it's searching. After that, it's just a matter of dealing with the $matches array, right?

Thanks, Mark


回答1:


Okay, here some example code with preg_match_all() that shows how to remove the nesting as well:

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

As $foundCities is now a simple array, you can iterate over it directly as well:

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

No need for a nested loop as the $matches return value has been normalized already. The concept is to make the code return / create the data as you need it for further processing.



来源:https://stackoverflow.com/questions/6351190/using-preg-match-to-find-all-words-in-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!