问题
I have migrated my contents from a Yii site to Wordpress and I have all my posts filled with div tags with all kind of styles and ids and class and I want to use a pattern to remove them all. I searched the internet and came with this function, yet it does remove the closing tag, but not the opening tags which contains other attributes like style id or class:
function remove_divs($data) {
$filteredContent = preg_replace(array('/<\s*div.*?>/', '</div>'), '', $data['post_content']);
$data['post_content'] = $filteredContent;
return $data;
}
add_filter('wp_insert_post_data', 'remove_divs', 99);
Can you help me figure what isn't working?
回答1:
Being inspired by the previous answer, I edited my function and it worked just fine. Here is the code:
function remove_divs($data) {
$filteredContent = preg_replace(array('/<\s*div[^>]*>/', '</div>'), '', $data['post_content']);
$data['post_content'] = $filteredContent;
return $data;
}
add_filter('wp_insert_post_data', 'remove_divs', 99);
Thank you for your answer!
回答2:
You can try this pattern
$pattern = "/<div[^>]*>(.*?)<\/div>/";
$content = '<div class="test">Alpha Beta Gamma</div>Test<div class="best">Delta Gamma Eta</div>';
preg_match_all($pattern, $content, $match);
var_dump($match);
来源:https://stackoverflow.com/questions/40410711/how-to-remove-div-tags-from-post-contents