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
The preg_match() function returns whether a match was found in a string.
Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .
The preg_match() function returns true if pattern matches otherwise, it returns false.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With