Preg_match_all foreach to return comma separated strings

Viewed 24

I have a text string and a list of words as key => word to match if any of the words are present in the string. If words are present, I would like to output a comma separated list of all the corresponding keys.

Here is my code:

<?php

$content = "They were FRIENDS. JAKE and JANE make a CAKE.";



$general_outcomes = [
    '1' => 'FRIENDS',
    '2' => 'CAKE',
    '3' => 'JANE',
    '4' => 'JAKE',
    '5' => 'MEGAN' // not present
];

foreach ($general_outcomes as $slug => $outcome) {
    preg_match_all('/\b'.$outcome.'\b/u', $content, $match);
    if (count($match[0]) >= 1) {
        return $slug;

   }
}

This code is echoing the keys without any separator like this:

1234

while the desired result is like this:

1,2,3,4

Please note that there should not be a trailing comma at the end of the list.

Thakn you very much!

1 Answers

You could add all matching indices to an array and then join it by comma:

$matches = [];
foreach ($general_outcomes as $slug => $outcome) {
    preg_match_all('/\b'.$outcome.'\b/u', $content, $match);
    if (count($match[0]) >= 1) {
        array_push($matches, $slug);
    }
}

$output = join(",", $matches);
echo $output;  // 1,2,3,4
Related