Replacing text in a string with recursion and regex

I am using tags to replace text before displaying output in a browser, similar to WordPress’ short codes.

Example string: Hi, this is a block of text {{block:welcome}} and this is a system variable {{variable:system_version}}

I have functions to replace these blocks accordingly, and I realize a foreach or while function will be the best way to deal with it, but unfortunately, replacing one {{...}} may introduce another. Hence, I opted for recursion until no more are found. Typical recursion is only once, but I have had two in one scenario. Maybe calling the function 3 times will work, but it sounds “wrong”.

Now that is where the problem occurs: I do NOT want to replace them when they appear in:

1) A page where the URL you are calling contains something 2) Any form element such as `<input>` or `<textarea>`. 

I need help on how to exclude from #2 above by means of a regex.

My regex currently look like this: ^\{\{((?!keep).)*$ (I realize it may still be wrong, or need modification – does not quite work yet).

If the item contains “keep”, e.g., {{block:welcome:keep}} it should not be replaced, but when doing so, the recursion never stops, as I keep finding items to replace, and thus run out of memory, or get maximum nested level errors.

The reason why I want to do this, is because I do not want the content replaced when on an ADMIN page, or when you are editing form content.

Someone willing to give it a crack? I am using PHP, if that matters.

Thanks!