我想根据使用STR_REPLACE在TXT文件中创建的列表来过滤字符串中的关键字(使用逗号分隔符)。
如果您在TXT列表中找到关键字,那么它将从字符串中删除。
$db_tag_new = str_replace('The,',"",$db_tag);
我的字符串:(每个单词都有一个逗号分隔符)
$db_tag="The,To,In,A,Of,Is,That,Will,And,Be,For,Rates,Or,Bank,0,It,More,Brexit,With,At,Has,Eu,Have,Said,Would,As,This,Britain,He,May,On,Pound,Are,Interest,Carney,By,They,But,Getty,First,Images,Vote,About,Leave,Even,Inflation,S,Up,Also,Negative";
thebadlist.txt :(每行新行)
The
To
In
A
Of
Is
That
Will
And
结果:
$db_tag="Rates,Bank,Brexit,Britain,Pound,Interest,Carney";
提前致谢
答案 0 :(得分:3)
使用file()
读取您的list.txt
,它会将每行读入数组。然后你可以使用str_replace()
,因为它允许param1和param2成为数组,尽管你只需要为parameter1使用数组
<?php
$db_tag="The,To,In,A,Of,Is,That,Will,And,Be,For,Rates,Or,Bank,0,It,More,Brexit,With,At,Has,Eu,Have,Said,Would,As,This,Britain,He,May,On,Pound,Are,Interest,Carney,By,They,But,Getty,First,Images,Vote,About,Leave,Even,Inflation,S,Up,Also,Negative";
$filters = file('list.txt');
// add commas to the occurances
for ($i=0; $i<count($filters); $i++) {
$filters[$i] = rtrim($filters[$i]) . ',';
}
$db_tag = str_replace($filters, '', $db_tag);
echo $db_tag.PHP_EOL;
包含
的list.txt
文件
The
To
In
A
Of
Is
That
Will
And
Or
结果:
是,,汇率,银行,0,IT,更多,Brexit,随着在,有,欧盟,有无,说,将,至于,这,英国,他,五月,开,英镑,正,利息,卡尼,通过,他们,但是,盖蒂,首先,图片,投票,关于休假,即使是,通货膨胀,S,最多,此外,负