This is a fairly complex PHP (rather than WP) issue if you want to take into account all possibilities.
If you replace test
with <a href="#">test</a>
you will run into problems if the content already has <a href="https://wordpress.stackexchange.com/questions/317374/?">test</a>
, because the result will then be <a href="https://wordpress.stackexchange.com/questions/317374/?"><a href="#">test</a></a>
So, before you do the replace you will need to see if test
is already a link. This is not that simple, because you cannot simply scan for <a href="https://wordpress.stackexchange.com/questions/317374/...">test</a>
. After all, you may have something like <a href="https://wordpress.stackexchange.com/questions/317374/...">this is my test, yeah!
. Or test
may be a substring of another word, like protesting
. To prevent the latter being targeted you might check for test
, but then you may miss test,
.
Another thing to consider: if there already is a link around test
, do you want to keep that one or replace it?
So, depending on you needs you will have to build a regular expression that does complex pattern recognition on your content to make sure it does exactly what you need. For help with regular expressions, try Stack Overflow.