As written in the commentary, I am posting this as an answer, hoping it will be useful to you.
You could try to replace the keyword in the text first, using a placeholder, and then, when all the text has been analyzed, you can replace these placeholders with real words.
For example, take the phrase:
"I have a car, a blue car."
We already ordered a list of keywords from longer to smaller, so we check the "blue car"; We find this in the text, so we place a placeholder and get:
"I have a car, a [[1]]."
The second keyword on the list is โcarโ; after substitution in the text we get:
"I have a [[2]], a [[1]]."
Finally, when all the keywords have been replaced, you only need to replace the placeholders in their order, using preg_replace in your function, and get the text with links.
source share