Ignore duplicates in regex pattern

I have a regular expression pattern that searches for words in a text file. How to ignore duplicates?

For example, look at this code.

$pattern = '/(lorem|ipsum|daboom|pahwal|ababaga)/i';
$num_found = preg_match_all( $pattern, $string, $matches );

echo "$num_found match(es) found!";
echo "Matched words: " . implode( ',', $matches[0] );

If I have more than one word lorem in an article, the output will be something like this

5 matches found!
Matched words: daboom,lorem,lorem,lorem,lorem

I want the template to detect only the first occurrence and ignore the rest, so the output should be:

2 matches found!
Matched words: daboom,lorem
+3
source share
1 answer

Do array_uniquein $matches[0]. And perhaps, array_mapwith strtolower, if you want unique was case-insensitive.

$pattern = '/(lorem|ipsum|daboom|pahwal|ababaga)/i';
preg_match_all( $pattern, $string, $matches );
$matches = $matches[0]?array_unique(array_map('strtolower', $matches[0])):array();

echo count($matches)." match(es) found!";
echo "Matched words: " . implode( ',', $matches );
+6
source

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


All Articles