首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >`content_save_pre`钩子无法仅用`preg_replace`函数替换内容

`content_save_pre`钩子无法仅用`preg_replace`函数替换内容
EN

Stack Overflow用户
提问于 2017-08-10 00:16:17
回答 1查看 508关注 0票数 0

在保存之前,我需要替换post_content中的代码块围栏。文章内容是在本地写的,然后推到github,然后是Wordpress。

在保存到Wordpress之前,我需要用:```js <some code> ```替换标记围栏[js] <some code> [/js]

参见我的工作报告:https://repl.it/KDz2/1,我的函数在Wordpress.之外运行得非常好。

Wordpress正在调用函数,但由于某种原因,替换失败了。我之所以知道这一点,是因为我可以让一个简单的str_replace在Wordpress中正常工作。

发行;

preg_replace未能在Wordpress过滤器中返回替换的内容。没有抛出错误。为什么会失败?

作为参考,我的functions.php文件包括:

代码语言:javascript
复制
add_filter( 'content_save_pre', 'markdown_code_highlight_fence');
function markdown_code_highlight_fence( $content ) {
  $newContent = preg_replace('/^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/m', '
      [${2}]
      $3
      [\\\${2}]
    ', $content);

  return $newContent;
}

也试过这个

代码语言:javascript
复制
function markdown_code_highlight_fence( $content ) {
  $newContent = preg_replace_callback('/^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/m', function($match){  
    $lang = $match[2] == '' ? 'js' : $match[2];
    return '
      ['.$lang.']'
      .' '.
      $match[3]
      .' '.
      '[\\'.$lang.']';  }, $content);

  return $newContent;
}
EN

回答 1

Stack Overflow用户

发布于 2017-08-10 11:43:26

不知道为什么preg_replace没有在Wordpress中工作。如果有人能帮我弄清楚,请帮我。

在此期间,我有以下工作解决办法:

代码语言:javascript
复制
add_filter( 'content_save_pre', 'markdown_code_highlight_fence_replace', 1, 1);
function markdown_code_highlight_fence_replace( $content ) {
  preg_match_all('/`{3,}(\S+)?/', $content, $matches);

  foreach ($matches[1] as $key=>$match) {
    if($match === '') continue;
    $content = preg_replace('/`{3,}/', '[/'.$match.']', $content, 2);
    $content = str_replace('[/'.$match.']'.$match, '['.$match.']', $content);
  }

  return $content;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45602531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档