Using preg_match to find all words in a list

With the help of SO, I was able to get the “keyword” from the subject line of the letter for use as a category. Now I decided to allow several categories for each image, but I can not correctly formulate my question in order to get a good answer from Google. preg_match stops at the first word in the list. I'm sure this has something to do with being “impatient” or just replacing the pipe symbol | by something else, but I just don't see it.
\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b .

The whole line I'm currently using is:

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

All I have to do is pull out all these words if they are present, as opposed to stopping in Amsterdam, or something else first in the subject that he is looking for. After that, it's just a question with the $ matches array, right?

Thanks Mark

+6
source share
1 answer

Ok, here is a sample code with preg_match_all() , which also shows how to remove nesting:

 $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 the first element of $matches $foundCities = $result ? $matches[0] : array(); printf("Found %d city/cities: %s.\n", count($foundCitites), implode('; ', $foundCities)); 

Since $foundCities now a simple array, you can also $foundCities over it directly:

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

There is no need for a nested loop, since the return value of $matches already normalized. The concept is to return the code / create the data as you need for further processing.

+1
source

Source: https://habr.com/ru/post/890556/


All Articles