Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using preg_match to find all words in a list

Tags:

php

preg-match

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

like image 503
Mark Avatar asked Jun 14 '11 23:06

Mark


People also ask

What is the use of Preg_match () method?

The preg_match() function returns whether a match was found in a string.

What value is return by Preg_match?

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 .

Which of the following call to Preg_match will return true?

The preg_match() function returns true if pattern matches otherwise, it returns false.


1 Answers

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.

like image 112
hakre Avatar answered Oct 19 '22 08:10

hakre