使用PHP regex将CSS类添加到HTML标记

Can anyone suggest the best way to add a CSS class to an HTML element using PHP?

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 <figure> 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.

For example, I could have:

<figure id="foo" data-track="bar" class="fig">

or

<figure class='fig bah' id='foo' data-track='bar'>

or

<figure data-track="bar">

or just

<figure>

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

if ( strpos( trim( $content ), '<figure' ) == 0 ) {

}

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 <figure> 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!

Edit = = = = = = = =

In answer to Amit's question here's an example of the desired input / output

<figure> to <figure class="big-image">

<figure class='boo'> to <figure class='big-image boo'>

<figure id="bar" class="boo"> to <figure id="bar" class="big-image boo">

I am not on system now so cannot write a code but just follow a simple procedure.

  1. get the post content in a variable using "the_content" or whatever you like.
  2. check if "<figure" come in the content.
  3. Read the string starting from "<figure" to first ">" char by char and save them in other variable lets say $remove_it .
  4. Now using $remove_it preg replace the post content.
  5. Resulting variable will return the required result.

If you have any other query contact me directly on my new blog http://www.sourabhmodi.in/. I will be happy to help you out.