you include the underscore in the preg_replace() function:
preg_replace("/[^A-Za-z0-9_]/"
dont include the underscore in the pregreplace function, you are replacing it with a blank there so it cannot be found in the result that the replace function is using.