title: PHP preg_replace replace text unless inside brackets
body: <p>I would like to use PHP's <code>preg_replace()</code> to search a text for occurrences of a certain word, and enclose that word in brackets, unless there are already brackets present. The challenge here is that I want to test for brackets that may or may not be directly adjacent to the text I am looking for.</p>
  
  <p>Random example: I want to replace <code>warfarin</code> with <code>[[warfarin]]</code></p>
  
  <ol>
  <li>in this string: <code>Use warfarin for the prevention of strokes</code></li>
  <li>but <strong>not</strong> in this string: <code>Use [[warfarin]] for the prevention of strokes</code> (brackets already present)</li>
  <li>and <strong>not</strong> in this string either: <code>Use [[generic warfarin formulation]] for the prevention of strokes</code> ('remote' brackets already present)</li>
  </ol>
  
  <p>I can satisfy the first two requirements all right using lookbehind and lookahead assertions:
  </p>
  
  <pre class="lang-sh prettyprint-override"><code>php &gt; echo preg_replace( "/(?&lt;!\[\[)(warfarin)(?!]])/", "[[$1]]", "Use warfarin for the prevention of strokes" );
  Use [[warfarin]] for the prevention of strokes
  php &gt; echo preg_replace( "/(?&lt;!\[\[)(warfarin)(?!]])/", "[[$1]]", "Use [[warfarin]] for the prevention of strokes" );
  Use [[warfarin]] for the prevention of strokes
  </code></pre>
  
  <p>But I need your help with the third requirement, i.e. not adding brackets when there are 'remote' brackets present:</p>
  
  <pre class="lang-sh prettyprint-override"><code>php &gt; echo preg_replace( "/(?&lt;!\[\[)(warfarin)(?!]])/", "[[$1]]", "Use [[generic warfarin formulation]] for the prevention of strokes" );
  Use [[generic [[warfarin]] formulation]] for the prevention of strokes
  </code></pre>
  
  <p>In this last example, the square brackets should <strong>not</strong> be added to the word <code>warfarin</code> since it is contained in a longer expression that is already enclosed in brackets.</p>
  
  <p>The problem is that PHP's regexp assertions must have fixed length, otherwise it would be very simple.</p>
  
  <p>I'm using</p>
  
  <pre class="lang-sh prettyprint-override"><code>PHP 5.3.10-1ubuntu3.1 with Suhosin-Patch (cli) (built: May  4 2012 02:20:36)
  </code></pre>
  
  <p>Thanks in advance!</p>