EDIT: I now see I was completely incorrect with my first solution, so I've removed it Let me review your code further...
EDIT2: Looks like you want a simple eregi_replace? Get rid of all that code and try this:
$themodifiedhtml1 = eregi_replace('\\.jpg?[0-9]+"', '\\.jpg?"', $theoriginalhtml);
That will take everything that looks like .jpg?34235135234" and turn it into .jpg?". If you dont want the ending question mark, change '.jpg?"', to '.jpg"',. The new HTML was stored in $themodifiedhtml1 in my example. Feel free to tweak the variable names to your liking.