I want to create a PHP function which will replace certain words out of a text with internal links. That works so far, but if I have two matches, I end up with invalid HTML code
Instead of using a loop, construct a single regular expression and modify your entire document in a single pass. That is, instead of these regular expressions:
~\b(foo)\b~i
~\b(bar)\b~i
~\b(baz)\b~i
Use just this one:
~\b(foo|bar|baz)\b~i
You might want to look at using implode to contruct the regular expression.
You also need to be careful of characters that have a special meaning inside a regular expression. You may find preg_quote useful for this.