我正在Wordpress网站上的亵渎过滤器上工作。当我使用普通数组时一切正常例如:str_replace(“ world”,“ Peter”,“ Hello world!”);
但是,我在使用关联数组时遇到问题。任何建议将不胜感激!
function customforumcontent($content) {
$censored = get_field('banned_words_list', 'option'); // Gets text field of comma seperated values
$censored = explode(",", $censored); // Create an associative array
$replace = '<b>[censored]</b>'; // Word to replace the banned word(s)
$content = str_ireplace(array_keys($censored), $replace, $content); // Where my problem seems to be occurring
return $content;
}
add_filter('asgarosforum_filter_post_content', 'customforumcontent');
尝试将preg_replace
与不区分大小写的标志一起使用:
$content = preg_replace("~".implode("|",$cencored)."~i", $replace, $content);
第一步,请替换:
$censored = get_field('banned_words_list', 'option');
使用:
$censored = get_field('banned_words_list');
如果您处于循环状态,这应该没有帖子ID即可工作。如果您不在循环中,则需要添加帖子ID,例如:
$censored = get_field('banned_words_list', $post_id);
// $post_id will need to be defined!
然后您可以添加以下结果:
$censored = get_field('banned_words_list');
echo $censored; // What does this output?
关于您的问题,我们可以看到您目前正在得到什么?
根据您的评论,听起来您只需要替换:
array_keys($censored);
使用
$censored
例如:
$content = str_ireplace($censored, $replace, $content);
根据对您的问题的评论,$ censored不是关联数组,因此array_keys($ censored)仅为[0,1,2 ...]。相反,您需要实际的数组,它只是$ censored。
这对我有用:
$content = 'I have a red car and a blue face';
$censored = 'red,blue'; // Gets text field of comma seperated values
$censored = explode(",", $censored); // Create an array
$censored = array_map ('trim', $censored); // Remove any leading or trailing whitespace
$replace = 'green'; // Word to replace the banned word(s)
$content = str_ireplace($censored, $replace, $content);
echo $content; // I have a green car and a green face
也许将其粘贴到您的代码中并一次调整一行以查看问题出在哪里