title: Identify and replace pairs of shortcoded variables within a string in PHP using preg_replace
body: <p><em>Before anyone asks, I have spent an hour trying to find a solution on SO and nothing seems to achieve exactly what I want... if it's out there, I apologise!</em></p>
  <p>So... I am trying to run preg_replace on a bunch of text to replace pairs of shortcodes.</p>
  <p>Example text:</p>
  <pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.
  [img]Abc123[/img][cap]This is an image[/cap]
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.
  [img]321cbA[/img][cap]This is also an image[/cap]
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.
  </code></pre>
  <p>I want to take each image and caption together and replace them as such:</p>
  <pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.
  &lt;img src=&quot;Abc123.jpg&quot; alt=&quot;This is an image&quot; /&gt;
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.
  &lt;img src=&quot;321cbA.jpg&quot; alt=&quot;This is also an image&quot; /&gt;
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.
  </code></pre>
  <p>The code I need will be along the lines of:</p>
  <pre><code>$text=&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.
  [img]Abc123[/img][cap]This is an image[/cap]
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.
  [img]321cbA[/img][cap]This is also an image[/cap]
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.&quot;;
  
  $pattern = '/\[(img)\](.*?)\[\/\1\]?/';
  // This doesn't work: $pattern = '/\[(img)\](.*?)\[\/\1\]\[(cap)\](.*?)\[\/\4\]?/';
  
  $replacement = '&lt;img src=&quot;$2.jpg&quot; alt=&quot;Help&quot; /&gt;';
  // &quot;Help&quot; will be $5 when we get both values
  
  echo preg_replace($pattern, $replacement, $text);
  </code></pre>
  <p>This code picks up one value but I cannot for the life of me get the pattern to pick up both values (commented line above is as far as I've got). I've tried dozens of SO pages and other websites but nothing seems to work. No doubt the corrected pattern will be simple but if someone could put me out of my misery I would greatly appreciate it!</p>
  <p>Thanks for your time.</p>