Here is a demonstration of how to use preg_replace_callback() to replace the gameid shortcode tags in your (I assume Joomla) articles.
You state in your question that the number of gameids will either be one or three. For this reason, you should not be using the {1,3} quantifier syntax because that means "one to three" instead of "one or three". In other words, the correct pattern will require that the second and third ids both/neither exist.
The whole shorttag is matched, so all you need to do is dictate the translation in the callback parameter of the native function.
Code: (Demo)
$articleText = <<<TEXT
Some article text
Triple id: {gameid 45735 76352 87262}.
Do not honor {gameid 12345 67890} because contains exactly 2 game ids!
unknown id: {gameid 66666} can't replace it!
Found single id: {gameid 76352}
finished the article
TEXT;
$gamesLookup = [
45735 => 'Pac-man',
76352 => 'Donkey Kong',
87262 => 'Rampage'
];
echo preg_replace_callback(
'~{gameid (\d{5})(?: (\d{5}) (\d{5}))?}~',
function ($m) use ($gamesLookup) {
echo 'm = ' . var_export($m, true) . "\n---\n";
return 'Game Name(s): ' . strtr(implode(', ', array_slice($m, 1)), $gamesLookup);
},
$articleText
);
Output: (I am printing out the matches arrays so you can see the data that you will need to access)
m = array (
0 => '{gameid 45735 76352 87262}',
1 => '45735',
2 => '76352',
3 => '87262',
)
---
m = array (
0 => '{gameid 66666}',
1 => '66666',
)
---
m = array (
0 => '{gameid 76352}',
1 => '76352',
)
---
Some article text
Triple id: Game Name(s): Pac-man, Donkey Kong, Rampage.
Do not honor {gameid 12345 67890} because contains exactly 2 game ids!
unknown id: Game Name(s): 66666 can't replace it!
Found single id: Game Name(s): Donkey Kong
finished the article
If you simply want a preg_match_all() call, then the same pattern will suffice...
Code: (Demo)
var_export(
preg_match_all('~{gameid (\d{5})(?: (\d{5}) (\d{5}))?}~', $articleText, $m, PREG_SET_ORDER)
? $m
: []
);
{gameid\s([0-9]{5}\s?){1,3}}possibly(?<game>gameid(?:.\d{5}){1,3})?