Backslashing in MODIFY_TYPE had no effect.

Added separate replace for spaces to escape them.
Also noticed that $val was used in foreach instead of $r.
Tested changes on my database - it worked.