Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如果包含一个单词,请删除整个单词_Php - Fatal编程技术网

Php 如果包含一个单词,请删除整个单词

Php 如果包含一个单词,请删除整个单词,php,Php,可能重复: 如何删除包含一个单词的整个单词? 例如,“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'; fore

可能重复:

如何删除包含一个单词的整个单词? 例如,“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;

我会使用这个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
也是数组的名称)

您可以循环使用
$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的答案。

这样试试

$_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 ) );

第二种方法避免了正则表达式的问题,如果一些保留字符出现在单词中。

@AD7six-Escaping\在这种情况下不会改变任何东西。将
$wordlist
放入模式中,确实会改变其含义。@AD7six同意并感谢您的解释,我仍在学习PHP。我相应地修正了我的答案。只是有点困惑。。。第二种方法——在一次替换中完成所有操作——可以单独使用,对吗?不需要循环等。对吗?@Norman很抱歉不清楚,我修正了答案。@OlafDietsche在原始代码
$wordlist
中是一个数组,但它在函数
clean
中也被重新定义,在函数
clean
中它只是一个变量,因为在clean函数之外已经有了一个
foreach
。但是我认为最好把foreach移到里面,这样你的答案是正确的。我会使用
\w*$wordlist\w*
,因为\w意味着boudary\b@AD7six$wordlist不是问题中的数组,因为它是在函数中重新定义的。可能有更好的解决方案,但代码会起作用。@Eineki您是对的,谢谢,\b是多余的,因为有\w*already@fthiella抱歉-中存在误导性的变量名称question@AD7six没问题,问题不清楚,但我编辑了我的答案,让它更明显,无论如何,我认为Olaf的方法在这种情况下更好!