Parsing and modifying HTML properly using the standard PHP library is quite a pain. There are many gotchas. Here’s a well documented example that will add the img-fluid
class to all images in the content.
To ensure that the doctype and HTML tags are not added to the HTML fragment a solution from this StackOverflow answer is used:
$dom->loadHTML( $content ), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
Note that there are other ways of doing this which are discussed in the SO post I linked to, but this soltion has worked well for me.
The code I’ve posted below expands on this solution to deal with utf8 characters as well.
/**
* Adds img-fluid class to images in content.
* Fire late to affect gallery images.
*/
add_filter( 'the_content', 'add_responsive_class', 9999 );
add_filter( 'acf_the_content', 'add_responsive_class', 9999 );
function add_responsive_class( $content ) {
// Bail if there is no content to work with.
if ( ! $content ) {
return $content;
}
// Create an instance of DOMDocument.
$dom = new \DOMDocument();
// Supress errors due to malformed HTML.
// See http://stackoverflow.com/a/17559716/3059883
$libxml_previous_state = libxml_use_internal_errors( true );
// Populate $dom with $content, making sure to handle UTF-8, otherwise
// problems will occur with UTF-8 characters.
// Also, make sure that the doctype and HTML tags are not added to our HTML fragment. http://stackoverflow.com/a/22490902/3059883
$dom->loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
// Restore previous state of libxml_use_internal_errors() now that we're done.
libxml_use_internal_errors( $libxml_previous_state );
// Create an instance of DOMXpath.
$xpath = new \DOMXpath( $dom );
// Get images.
$imgs = $xpath->query( "//img" );
// Add additional classes to images.
foreach ( $imgs as $img ) {
$existing_class = $img->getAttribute( 'class' );
$img->setAttribute( 'class', "{$existing_class} img-fluid" );
}
// Save and return updated HTML.
$new_content = $dom->saveHTML();
return $new_content;
}