我有两个数组,单词和stop_words。我想使用stop_words来查看单词中的匹配项,并用w ** 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 )
所以迪克应该变成d ** k。在我目前的实现中,我只需用4个星号改变一切......这是不希望的......
答案 0 :(得分: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>';
答案 1 :(得分: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) );