I have a block of html code as a string in PHP and I want to replace certain text and phrases with links. The problem is some of the phrases I want to replace already appear in tag attributes or existing links so a simple str_replace breaks the HTML.
For example:
<code><p>This is my website: test.com</p>
<p>Here is a link: <a href="https://www.test.com/hello">Click here</a></p>
</code>
<code><p>This is my website: test.com</p>
<p>Here is a link: <a href="https://www.test.com/hello">Click here</a></p>
</code>
<p>This is my website: test.com</p>
<p>Here is a link: <a href="https://www.test.com/hello">Click here</a></p>
Using PHP str_replace to replace test.com with an html link like this:
<code>$output = str_replace('test.com', '<a href="https://www.test.com/">test.com</a>', $input);
</code>
<code>$output = str_replace('test.com', '<a href="https://www.test.com/">test.com</a>', $input);
</code>
$output = str_replace('test.com', '<a href="https://www.test.com/">test.com</a>', $input);
Gives this output:
<code><p>This is my website: <a href="https://www.test.com/">test.com</a></p>
<p>Here is a link: <a href="https://www.<a href="https://www.test.com/">test.com</a>/hello">Click here</a></p>
</code>
<code><p>This is my website: <a href="https://www.test.com/">test.com</a></p>
<p>Here is a link: <a href="https://www.<a href="https://www.test.com/">test.com</a>/hello">Click here</a></p>
</code>
<p>This is my website: <a href="https://www.test.com/">test.com</a></p>
<p>Here is a link: <a href="https://www.<a href="https://www.test.com/">test.com</a>/hello">Click here</a></p>
I have many phrases/strings to replace in a loop. How can I replace only the occurrences that are not already within an html a tag or an attribute?
1