将 table 标签包裹在 div 标签周围

G.d*_*ism 4 wordpress

我尝试使用这段代码在帖子内容中的每个表标签周围包裹一个 div 标签,但我不知道为什么它不起作用:

function tekst_wrapper($content) {
  return preg_replace_callback('~<table.*</table>~i', function($match) {
    return '<div>' . $match[0] . '</div>';
  }, $content);
}

add_filter('the_content', 'tekst_wrapper');
Run Code Online (Sandbox Code Playgroud)

Nik*_*cic 5

您应该尝试在通配符后使用问号(零个或多个空格),在“i”标志后使用“s”标志。第一个更改应该帮助您的正则表达式函数区分带或不带空格和属性的表标记的变体。其次应该在正则表达式搜索中包含换行符:

~<table.*?</table>~is
Run Code Online (Sandbox Code Playgroud)

完整的代码是

function tekst_wrapper($content) {
  return preg_replace_callback('~<table.*?</table>~is', function($match) {
    return '<div>' . $match[0] . '</div>';
  }, $content);
}

add_filter('the_content', 'tekst_wrapper');
Run Code Online (Sandbox Code Playgroud)