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">