Skip to content

Instantly share code, notes, and snippets.

@ramsesdelr
Created June 28, 2024 22:48
Show Gist options
  • Select an option

  • Save ramsesdelr/71d92b2675ca9f810447c18532e04479 to your computer and use it in GitHub Desktop.

Select an option

Save ramsesdelr/71d92b2675ca9f810447c18532e04479 to your computer and use it in GitHub Desktop.
<?php
/**
* Creates a DOM Document based on the content.
*
* @param string $content The post content.
* @param string The modified HTML.
*/
function dom_add_strong_class( $content ) {
// Create a new DOMDocument object.
$doc = new DOMDocument();
libxml_use_internal_errors( true );
// Load the HTML content.
$doc->loadHTML( $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
$xpath = new DOMXPath( $doc );
// Find all <strong> and <b> tag.
$strong_tags = $xpath->query( '//b | //strong' );
foreach ( $strong_tags as $strong_tag ) {
if ( $strong_tag->hasAttribute( 'class' ) ) {
$current_classes = $strong_tag->getAttribute( 'class' );
$strong_tag->setAttribute( 'class', $current_classes . ' extra-strong' );
} else {
$strong_tag->setAttribute( 'class', 'strong' );
}
}
// Save the modified HTML.
$modified_html = $doc->saveHTML();
return $modified_html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment