使用PHP删除包含特定单词/短语的行

Jim*_*mmy 5 php text

伙计们我有一个文本文件,我想删除一些包含特定单词的行

 <?php
// set source file name and path
$source = "problem.txt";

// read raw text as array
$raw = file($source) or die("Cannot read file");
Run Code Online (Sandbox Code Playgroud)

现在有一个数组,我想删除一些行,并希望使用它们等.

Pas*_*TIN 7

当您将文件的每一行放在一个数组的行中时,该array_filter函数可能会引起您的兴趣(引用):

array array_filter  ( array $input  [, callback $callback  ] )
Run Code Online (Sandbox Code Playgroud)

迭代输入数组中的每个值,将它们传递给回调函数.
如果回调函数返回true,则输入中的当前值将返回到结果数组中.数组键被保留.

您可以使用strposstripos确定字符串是否包含在另一个字符串中.

例如,假设我们有这个数组:

$arr = array(
  'this is a test',
  'glop test',
  'i like php',
  'a badword, glop is', 
);
Run Code Online (Sandbox Code Playgroud)

我们可以定义一个回调函数来过滤掉包含" glop"的行:

function keep_no_glop($line) {
  if (strpos($line, 'glop') !== false) {
    return false;
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)

并使用该功能array_filter:

$arr_filtered = array_filter($arr, 'keep_no_glop');
var_dump($arr_filtered);
Run Code Online (Sandbox Code Playgroud)

我们得到这种输出:

array
  0 => string 'this is a test' (length=14)
  2 => string 'i like php' (length=10)
Run Code Online (Sandbox Code Playgroud)

即我们删除了包含"badword""glop"的所有行.


当然,既然你有基本的想法,没有什么能阻止你使用更复杂的回调函数;-)


评论后编辑:这是应该有效的代码的完整部分:

首先,你有你的行列表:

$arr = array(
  'this is a test',
  'glop test',
  'i like php',
  'a badword, glop is', 
);
Run Code Online (Sandbox Code Playgroud)

然后,你从一个文件中加载坏词列表:
你修剪每一行,并删除空行,以确保你最终只有$bad_words数组中的"单词" ,而不是会导致麻烦的空白.

$bad_words = array_filter(array_map('trim', file('your_file_with_bad_words.txt')));
var_dump($bad_words);
Run Code Online (Sandbox Code Playgroud)

$bad_words数组包含来自我的测试文件:

array
  0 => string 'glop' (length=4)
  1 => string 'test' (length=4)
Run Code Online (Sandbox Code Playgroud)

然后,回调函数循环遍历那些坏词:

注意:使用全局变量不是那么好:-(但是调用的回调函数array_filter没有获得任何其他参数,并且我不希望每次调用回调函数时都加载该文件.

function keep_no_glop($line) {
  global $bad_words;
  foreach ($bad_words as $bad_word) {
      if (strpos($line, $bad_word) !== false) {
        return false;
      }
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)

而且,和以前一样,您可以使用array_filter过滤线:

$arr_filtered = array_filter($arr, 'keep_no_glop');
var_dump($arr_filtered);
Run Code Online (Sandbox Code Playgroud)

这一次,给你:

array
  2 => string 'i like php' (length=10)
Run Code Online (Sandbox Code Playgroud)