mysql_real_escape_string is an example of “escaping”, ie protecting the next environment which is about to receive some data.
Your ip preg_replace() example could be described as “filtering”, ie only allowing in what you expect and in this case, removing what is not explicitly allowed in digits and a dot.
The rule is called FIEO (Filter Input, Escape Output).
Do your best to filter incoming data, but no matter how confident you are you have filtered it correctly (mistakes can happen) get into the habit of escaping the output for the next environment.
This applies to any user-generated input, and this includes anything coming from GET, POST, COOKIES and so on.
if the next environment is a webpage, as html, then use the [fphp]htmlentities[/fphp] family of escape options.
Bang FIEO into your head till you get it, it is critical when working on the web.
Have a mental picture of stuff coming into PHP from one end of a pipe, and going somewhere else out the other end.