文章最后更新时间:

把代码放到后台func.php或者functions.php文件里后,文章里的某个文字就会改变颜色
代码一
// 批量替换文章中指定文字并添加颜色样式
add_filter('the_content', 'batch_change_text_color');
function batch_change_text_color($content) {
// 要替换的关键词数组,可自行添加更多
$keywords = array(
'自闭',
'抑郁症',
'焦虑'
);
// 替换后的样式
foreach ($keywords as $keyword) {
$replacement = '<span style="color: #ff0000; font-weight: bold;">' . $keyword . '</span>';
$content = str_replace($keyword, $replacement, $content);
}
return $content;
}
代码二
批量更改字体颜色后,还可以替换文字内容
// 批量替换文章中指定文字,同时修改颜色和内容
add_filter('the_content', 'batch_change_text_color_and_content');
function batch_change_text_color_and_content($content) {
// 定义需要替换的关键词及对应的替换内容(包含颜色样式)
$replacements = array(
'自闭' => '<span style="color: #ff0000; font-weight: bold;">自闭症谱系障碍</span>',
'抑郁症' => '<span style="color: #0000ff; font-weight: bold;">抑郁障碍</span>',
'焦虑' => '<span style="color: #ff9900; font-weight: bold;">焦虑情绪</span>'
);
// 处理替换,避免重复替换已处理的内容
foreach ($replacements as $keyword => $replacement) {
// 提取替换后的文本内容(去除HTML标签)
$cleanReplacement = strip_tags($replacement);
// 构建正则表达式,排除已替换的内容
$pattern = '/(?!' . preg_quote('<span', '/') . '.*?)' . preg_quote($keyword, '/') . '(?!.*?' . preg_quote('</span>', '/') . ')/';
// 执行替换
$content = preg_replace($pattern, $replacement, $content);
}
return $content;
}
© 版权声明
© 版权声明 All Rights Reserved
THE END










暂无评论内容