如何从ACF字段转换逗号分隔的字符串以在str_ireplace中使用

问题描述 投票:1回答:2

我正在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');
php wordpress advanced-custom-fields
2个回答
0
投票

尝试将preg_replace与不区分大小写的标志一起使用:

$content = preg_replace("~".implode("|",$cencored)."~i", $replace, $content);

0
投票
  1. 您能确认'banned_words_list'是标准文本字段,而不是例如转发器字段吗?
  2. 第一步,请替换:

    $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!
    
  3. 然后您可以添加以下结果:

    $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

也许将其粘贴到您的代码中并一次调整一行以查看问题出在哪里

© www.soinside.com 2019 - 2024. All rights reserved.