可能重复:
Remove entire word if the word contains specific string
如何删除包含单词的整个单词? 例如,'releas'应该删除已发布的,释放发布等。
/* Read in from the file here, not in the function - you only need to read the file once */
$wordlist = array('release','announce');
/* Sample data */
$words = 'adobe releases releases Acrobat X';
foreach ($wordlist as $v)
$words = clean($v,$words);
function clean($wordlist,$value)
{
return preg_replace("/\b$wordlist\b/i", '***',trim($value));
}
echo 'Words: '.$words.PHP_EOL;
答案 0 :(得分:3)
我会使用这个REGEXP;
return preg_replace("/\w*$wordlist\w*/i", '***', trim($value));
应用于您的代码,它将是:
foreach ($wordlist as $v)
$words = clean($v, $words);
function clean($word, $value) {
return preg_replace("/\w*$word\w*/i", '***',trim($value));
}
(请注意我已将$wordlist
重命名为$word
以使事情更清晰,因为$wordlist
也是数组的名称)
答案 1 :(得分:3)
您可以循环浏览$wordlist
function clean($wordlist,$value)
{
foreach ($wordlist as $word) {
$value = preg_replace("/\b\w*$word\w*\b/i", '***', trim($value));
}
return $value;
}
并在一次替换
function clean($wordlist,$value)
{
$all_words = implode('|', $wordlist);
return preg_replace("/\b\w*(?:$all_words)\w*\b/i", '***', trim($value));
}
更新:
通过其他答案和评论,我似乎无法正确看待这个问题。如果$wordlist
不是数组,您可以使用@ fthiella的答案。
答案 2 :(得分:0)
以这种方式试试
$_words = implode( '|', $wordlist );
return preg_replace( "/\b\w*{$_words}\w*\b/i", "***", trim( $value ) );
或更好
$_words = array();
foreach ( $wordlist as $word ) {
$_words[] = '/\b\w*' . preg_quote( $word ) . '\w*\b/i';
}
return preg_replace( $_words, '***', trim( $value ) );
第二种方法避免了正则表达式的问题,如果一些保留的字符出现在单词内。