I might be completely off base here, but could you just
do something like
$content =~ s!($code_regex)! $1.$href1.$i++.$href2!ge;
work? I think its probably cause your substituting stuff into content, making the string different when it tries to do a second match, that was causing it to do strange things. Just a thought - I haven't actually tried it out or anything.