You need to first extract the ids collectively, then make them into an array.
You could for example split the string using double quotes:
list (,$rawIds) = preg_split('#"#', $string);
and then explode the ids:
$ids = preg_split('#,\\s*#', $rawIds);
The \s* takes care of possible whitespaces (e.g. "21,22,23, 24,25").
At that point you use $ids as an array:
foreach ($ids as $index => $id) {
print "ID #{$index} is {$id}\n";
}
ID #0 is 5
ID #1 is 8
ID #2 is 12
However, you'd better verify how the string got created: e.g. if it is by any chance JSON, you'd be better served by using json_decode($string, true).