Why are you passing the IP in a hidden field, one that a user could simply change to be any IP they like?
And no, echo() outputs data while return() simply returns it to the calling function. If you modified that function so that it returned()'ed data instead, then yes, it could definitely work.
Otherwise, you might look into using [man]preg_replace_callback/man to call the function as Weedpacket suggested.