1

我有两个数组,单词和 stop_words。我想使用 stop_words 查看单词中的匹配项并用 aw**d 替换匹配项。

至今:

$words_arr = explode(",",$result[0]->words);
$words_stop_arr = json_decode($settings['words_stop']);
print_r(str_ireplace($words_stop_arr, "****", $words_arr));

words_arr ->

Array ( [0] => sex [1] => drugs [2] => rock [3] => lamba [4] => runner [5] => rule [6] => going [7] => war [8] => work [9] => eat [10] => program [11] => photography [12] => cart [13] => wart [14] => jungle [15] => dick )

和停用词->

Array ( [0] => dick [1] => orgy [2] => suck [3] => rape )

所以dick应该改成d**k。在我目前的实现中,我只需用 4 个星号更改所有内容......这是不希望的......

4

2 回答 2

1

这是一个根据您要查找的内容审查数组的函数:

function censorize(&$word, $k, $blacklist) {
    if(array_search($word, $blacklist) !== false) {
        $warr = str_split($word);
        $word = $warr[0]
                .implode('', array_fill(0, count($warr)-2, '*'))
                .end($warr);
    }
}

$words_arr      = array('allowed', 'censored', 'sex', 'drugs', 'rock', 'lamba', 'runner', 'rule', 'going', 'war', 'work', 'eat', 'program', 'photography', 'cart', 'wart', 'jungle', 'tick');
$words_stop_arr = array('censored', 'tick', 'orga', 'sack', 'rave');

array_walk($words_arr, 'censorize', $words_stop_arr);

echo '<pre>';
var_dump($words_arr);
echo '</pre>';

在 PHP 沙箱上检查它

于 2013-11-15T09:45:49.283 回答
0

一种稍微不同的基于字符串的方法,它不会修改原始数组:

function censor_words( $words ){
  static $censored; if ( !$censored ) {
    $censored = array_flip(array(
      'crazy', 'daffodil', 'example', 'list'
    ));
  }
  foreach ( $words as $key => $word ) {
    if ( isset($censored[$word]) ) {
      $words[$key] = str_pad($word{0},strlen($word)-1,'*').substr($word, -1);
    }
  }
  return $words;
}

用法:

$words_arr = array('hello', 'crazy', 'world', 'example', 'array');

print_r( censor_words($words_arr) );
于 2013-11-15T10:31:34.000 回答