not sure if it works in PHP that way but a really simple solution would be:
$string = preg_replace('/\ba\b\s([aeiou])/', 'an $1', $string);
$string = preg_replace('/\ban\b\s([^aeiou])/', 'an $1', $string);
(Not sure about the a/an rule as there is no such rule in german and i usually use the one that sounds better)
Explanation:
\b is a word boundary, so \ba\b looks for the word a, followed by a space and one of the letters [aeiou]. The letter is captured to $1 and the expression is replaced with an
followed by the captured letter.