需要帮助代码才能获得上述主题的结果,
到目前为止,我已经使用了这段代码
<?php
$data = file_get_contents("pg1-afcCup.txt");
$data = explode(" ", $data);
$remv = "Hosts";
foreach($data as $val) {
if($remv != $val) {
$newdata .= $val . " ";
// print "$val<br />\n";
}
}
$newdata = substr($newdata, 0, -1); // remove trailing ,
print "<br /><br />String: $newdata";
$fp = fopen("pg2-afcCup.txt", "w+");
$fw = fwrite($fp, $newdata);
fclose($fp);
?>
以上代码将删除区分大小写的&#34;主机&#34;在pg1-afcCup.txt中单词,并重写并保存在pg2-afcCup.txt中。
如何使其不敏感,并找到不止一个单词(用更多单词填充$ remv)?
ps:我试过preg_replace没有成功......
答案 0 :(得分:0)
试试这个
<?php
$data = file_get_contents("pg1-afcCup.txt");
$data = explode(" ", $data);
$remv = "hosts";
$newdata = "";
foreach($data as $val) {
if($remv != strtolower($val)) {
$newdata .= $val . " ";
// print "$val<br />\n";
}
}
$newdata = substr($newdata, 0, -1); // remove trailing ,
print "<br /><br />String: $newdata";
$fp = fopen("pg2-afcCup.txt", "w+");
$fw = fwrite($fp, $newdata);
fclose($fp);
?>
它将字符串转换为小写,然后检查。所以,这应该可以正常工作。
适用于多个过滤器
<?php
$data = file_get_contents("pg1-afcCup.txt");
$data = explode(" ", $data);
$remv = array("hosts","other", "somemore");
$newdata="";
foreach($data as $val) {
if (! in_array(strtolower($val),$remv) ) {
$newdata .= $val . " ";
// print "$val<br />\n";
}
}
$newdata = substr($newdata, 0, -1); // remove trailing ,
print "<br /><br />String: $newdata";
$fp = fopen("pg2-afcCup.txt", "w+");
$fw = fwrite($fp, $newdata);
fclose($fp);
?>
答案 1 :(得分:0)
您可以尝试使用preg_replace
<?php
$data = file_get_contents("pg.txt");
$data = explode(" ", $data);
$remv = "Hosts";
$pattern = '/^hosts$/i'; # if you need to erase the exact word
#$pattern = '/hosts/i'; # erasing a substring
foreach($data as $val) {
$newdata .= preg_replace($pattern, "", $val) . " ";
}
$newdata = substr($newdata, 0, -1); // remove trailing ,
print "<br /><br />String: $newdata";
$fp = fopen("pg2-afcCup.txt", "w+");
$fw = fwrite($fp, $newdata);
fclose($fp);
?>