title: Regular expression to ensure all links have target="_blank"
body: <p>I have a textarea which uses CKEditor to generate HTML. I want to ensure that all links the user enters have their <code>target="_blank"</code>. I thought I'd need to do two regex checks: one to replace any <code>target="..."</code> to <code>target="_blank"</code>, and another to just insert target attribute where target attribute doesn't exist. I'm not making much progress:</p>
  
  <pre><code>// where target attribute doesn't exist, add it
  preg_replace("/&lt;a(\s*(?!target)([\w\-])+=([\\"\'])[^\\"\']+\3)*\s*\/?&gt;/", "&lt;a target="_blank"$1&gt;", $input_lines);
  </code></pre>
  
  <p>This works in this simple case:</p>
  
  <pre><code>&lt;a href="#"&gt;one&lt;/a&gt; ---&gt; &lt;a target="_blank" href="#"&gt;one&lt;/a&gt;
  </code></pre>
  
  <p>It does not work for <code>&lt;a href="#" alt="hello"&gt;one&lt;/a&gt;</code>, I'm not sure why but then I don't normally do things this challenging with regular expressions.</p>
  
  <p>Also, how would I replace existing <code>target="..."</code> (e.g. <code>target="_parent</code>") with strictly <code>target="_blank</code>"?</p>