title: Add a CSS class to an HTML tag with PHP regex
body: <p>Can anyone suggest the best way to add a CSS class to an HTML element using PHP?</p>
  
  <p>I need to modify a string which is the content of a WordPress post. If the post has a figure element at the start, I want to extract the element's opening <code>&lt;figure&gt;</code> tag and add the CSS class "big-image" to it before putting it back in place. The tag may or may not have a class attribute (with a value in single or double quotes), and it may have other attributes in various orders, so I can't just use preg_replace: I'll need to pull the tag out and run it through some logic with conditions to allow for these possibilities.</p>
  
  <p>For example, I could have:</p>
  
  <p><code>&lt;figure id="foo" data-track="bar" class="fig"&gt;</code></p>
  
  <p>or</p>
  
  <p><code>&lt;figure class='fig bah' id='foo' data-track='bar'&gt;</code></p>
  
  <p>or</p>
  
  <p><code>&lt;figure data-track="bar"&gt;</code></p>
  
  <p>or just </p>
  
  <p><code>&lt;figure&gt;</code></p>
  
  <p>I only need to do this if the figure is the first thing in the content - if there's a figure anywhere else I'll ignore it. I've got as far as this first condition</p>
  
  <pre><code>if ( strpos( trim( $content ), '&lt;figure' ) == 0 ) {
  
  }
  </code></pre>
  
  <p>but I'm a bit baffled as to how to take it further. It seems to me I need a PHP function that'll use regex to find the first <code>&lt;figure&gt;</code> and split the $content string at the end of its opening tag, returning both halves. But there doesn't seem to be such a function - preg_split returns the string divided at the pattern, but not the pattern itself. I'd be grateful for any advice!</p>
  
  <p>Edit = = = = = = = = </p>
  
  <p>In answer to Amit's question here's an example of the desired input / output</p>
  
  <p><code>&lt;figure&gt;</code> to <code>&lt;figure class="big-image"&gt;</code></p>
  
  <p><code>&lt;figure class='boo'&gt;</code> to <code>&lt;figure class='big-image boo'&gt;</code></p>
  
  <p><code>&lt;figure id="bar" class="boo"&gt;</code> to <code>&lt;figure id="bar" class="big-image boo"&gt;</code></p>