Prevent infinite loops in replace_substring() and remove_substring()

* Prevent infinite loops in replace_substring() and remove_substring():
  * determine maximum number of iterations
  * limit do loops to that number