Вы находитесь в PHP, поэтому рассмотрите что-то вроде:
$words = explode(' ', "quick brown fox");
$out = array_map(process, $words);
return join(' ', $out);
и определить
function process($word) {
$p = strpos($word, 'gram');
if ($p === FALSE) return $word;
/// take apart pieces with substr and friends, reformat in HTML, and return them
$left = substr($word, 0, $p);
$match = substr($word, $p, strlen('gram'));
$right = substr($word, $p+strlen('gram'));
return some_function_of($left, $match, $right);
}
Немного больше усилий, но он делает то, что ты хочешь.