title: PHP RegEx: matching a word or sentence inside a html <p> BUT NOT inside <div> <img> <a> tags
body: <p>I'm trying to match and replace about 100 words inside an html document creating links for each word. For performance reasons, I think DOM manipulation will be slower than preg_replace.</p>
  
  <p>The thing is I want to be able to match (and replace) just simple words (or sentences) </p>
  
  <p><code>INSIDE &lt;p&gt; tags BUT NOT inside any other tag &lt;a&gt; &lt;div&gt; nor &lt;img&gt;.
  </code></p>
  
  <p>I'm using this regex expression to match the word "sapien":</p>
  
  <pre><code>/(&lt;p[^&gt;]*&gt;)(.*)(?!&lt;a\s[^&gt;]+&gt;[^&lt;\/a&gt;]+)(?!=\"[\w]*)(\bsapien\b)(?![^&lt;\/a&gt;]+&lt;\/a&gt;)(?![^\w]*\")(.*)(&lt;\/p&gt;)/imU
  </code></pre>
  
  <p>Here is the text where I'm applying it:</p>
  
  <pre><code>&lt;p&gt;Cras cursus consequat nibh &lt;a href="#"&gt;sapien&lt;/a&gt;ac vehicula. Sed erat sapien, condimentum quis risus nec, viverra dignissim nisi. Cras sapien convallis, erat egestas tincidunt &lt;img src="myimage.jpg" alt="sapien" &gt;rutrum, massa enim sagittis ante, sed pellentesque lorem risus vitae enim. Curabitur hendrerit dolor facilisis &lt;a href="sapien"&gt;sapien&lt;/a&gt; dolor malesuada molestie.&lt;/p&gt;
  </code></pre>
  
  <p>I'm getting the match in </p>
  
  <pre><code>&lt;a href="#"&gt;sapien&lt;/a&gt; 
  </code></pre>
  
  <p>which is inside  tag.</p>
  
  <p>Any help will be much appreciated. Thanks.</p>