title: How can I replace strings NOT within a link tag?
body: <p>I am working on this PHP function. The idea is to wrap certain words occuring in a string into certain tags (both, words and tags, given in an array). It works OK!, but when those words occur into a linked text or its 'src' attribute, then of course the link is broken and stuffed with tags, or tags that should not be inside a link are generated. This is what I have now:</p>
  
  <pre><code>function replace() {
    $terminos = array (
    "beneficios" =&gt; "h3",
    "valoracion" =&gt; "h2",
    "empresarios" =&gt; "h2",
    "tecnologias" =&gt; "h2",
    "...and so on..." =&gt; "etc",
    );
  
    foreach ($terminos as $key =&gt; $value)
    {
    $body = "string where the word empresarios should be replaced; but the word &lt;a href='http://www.empresarios.com'&gt;empresarios&lt;/a&gt; should not be replaced inside &lt;a&gt; tags nor in the URL of their 'src' attribute.";
    $tagged = "&lt;".$value."&gt;".$key."&lt;/".$value."&gt;";
    $result = str_replace($key, $tagged, $body);
    }
  }
  </code></pre>
  
  <p>The function, in this example, should return <code>"string where the word &lt;h2&gt;empresarios&lt;/h2&gt; should be replaced; but the word &lt;a href='http://www.empresarios.com'&gt;empresarios&lt;/a&gt; should not be replaced inside &lt;a&gt; tags nor in the URL of their 'src' attribute."</code></p>
  
  <p>I'd like this replacement function to work all throught the string, but not inside  tags <em>nor</em> in its attributes!</p>
  
  <p>(I'd like to do what is mentioned in the following thread, it's just that it's not in javascript what I need, but in PHP: <code>/questions/1666790/how-to-replace-text-not-within-a-specific-tag-in-javascript</code>)</p>