Here's an [aggregate replace function](https://github.com/jakethaw/replace_agg) I wrote several years ago. Disclaimer: I was relatively new to C when this was written, so no guarantees except for the fact that I've used it over the years and have not encountered any issues.