Capture-avoiding replacement function