How to remove <div> tags from post contents

拈花ヽ惹草 提交于 2020-03-06 04:32:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!