在保存之前,我需要替换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文件包括:
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;
}也试过这个
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;
}发布于 2017-08-10 11:43:26
不知道为什么preg_replace没有在Wordpress中工作。如果有人能帮我弄清楚,请帮我。
在此期间,我有以下工作解决办法:
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;
}https://stackoverflow.com/questions/45602531
复制相似问题