gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:36:46 26 4
gpt4 key购买 nike

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

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

// read raw text as array
$raw = file($source) or die("Cannot read file");

现在有一个数组,我想从中删除一些行并继续使用它们。

最佳答案

由于文件的每一行都在数组的一行中,因此 array_filter函数可能会让您感兴趣(引用):

array array_filter  ( array $input  [, callback $callback  ] )

Iterates over each value in the input array passing them to the callback function.
If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

你可以使用 strposstripos判断一个字符串是否包含在另一个字符串中。

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

$arr = array(
'this is a test',
'glop test',
'i like php',
'a badword, glop is',
);

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

function keep_no_glop($line) {
if (strpos($line, 'glop') !== false) {
return false;
}
return true;
}

然后将该函数与 array_filter 一起使用:

$arr_filtered = array_filter($arr, 'keep_no_glop');
var_dump($arr_filtered);

我们会得到这样的输出:

array
0 => string 'this is a test' (length=14)
2 => string 'i like php' (length=10)

即我们删除了所有包含“坏词”“glop”的行。


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


评论后编辑:这里是完整的代码部分:

首先,您有行列表:

$arr = array(
'this is a test',
'glop test',
'i like php',
'a badword, glop is',
);

然后,您从文件中加载坏词列表:
然后你修剪每一行,并删除空行,以确保你在 $bad_words 数组中只得到“单词”,而不是会引起麻烦的空白内容。

$bad_words = array_filter(array_map('trim', file('your_file_with_bad_words.txt')));
var_dump($bad_words);

$bad_words 数组包含,来 self 的测试文件:

array
0 => string 'glop' (length=4)
1 => string 'test' (length=4)

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

注意:使用全局变量不是很好:-( 但是 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;
}

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

$arr_filtered = array_filter($arr, 'keep_no_glop');
var_dump($arr_filtered);

这一次,给你:

array
2 => string 'i like php' (length=10)

关于php - 使用 PHP 删除包含特定单词/短语的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2267762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com