title: If condition inside preg_replace in PHP
body: <p>I want to add comment inside a replaced text only if condition is true.</p>
  
  <p>This is the basic code I work with.</p>
  
  <pre><code>&lt;?php
  $keepcomments="yes"; //yes or no
  $str="abcdefgh";
  $str = preg_replace("~abcd~", 'dcba "if($keepcomments=="yes"){ echo"-- some comments here --"} ', $str);
  echo $str;
  ?&gt;
  </code></pre>
  
  <p>I tried with :</p>
  
  <pre><code>if ($keepcomments=="yes"){ 
  $str = $str."&lt;-- some comments here --&gt;";
  }
  </code></pre>
  
  <p>The result is :</p>
  
  <pre><code>dcbaefgh-- some comments here --
  </code></pre>
  
  <p>But I have to <code>preg_replace</code> in more lines, problem is when I do that, all the comments are appearing at the end of result string.</p>
  
  <pre><code>dcbaefgh
  dcbaefgh
  dcbaefgh
  -- some comments here --
  -- some comments here --
  -- some comments here --
  </code></pre>
  
  <p>and I don't know how to use <code>preg_replace_callback()</code> in this case.</p>
  
  <p>Any help would be appreciated.</p>
  
  <h1>EDIT</h1>
  
  <p>When the string is "abcdefgh", i want to replace "abcd" in that string with "dcba". at the same time, if <code>$keepcomments</code> is yes, then i want to add a comment at the end of that string.
  and then i want to duplicate same code in few more lines. 
  Expected output is :</p>
  
  <pre><code>dcbaefgh-- some comments here --
  dcbaefgh-- some comments here --
  dcbaefgh-- some comments here --
  </code></pre>