Yes, I do understand that, and I'm suggesting actually manually altering the file to achieve what you want by a simple function call instead of dynamically rebuilding the php file each time.
But if you really want to go about it the hard way, use preg_match with the flag PREG_OFFSET_CAPTURE, read the file into a string, grab the substring from 0 to $match[0][1], concatenate with your additional code and concatenate with the file contents from $match[0][1].