Using preg_match to find all words in a list
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 o开发者_StackOverflow中文版f 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
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.
精彩评论