使用标准PHP库正确解析和修改HTML是一件非常痛苦的事情。有很多陷阱。下面是一个记录良好的示例,它将添加img-fluid
对内容中的所有图像初始化。
为确保doctype和HTML标记不会添加到HTML片段,请从this StackOverflow 答案是:
$dom->loadHTML( $content ), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
请注意,我链接到的SO帖子中讨论了其他方法,但这个解决方案对我很有效。
下面我发布的代码扩展了这个解决方案,以处理utf8字符。
/**
* 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;
}