PHP Remove/Replace 来自文本文件的字符串

PHP Remove/Replace string from a text file

如果我有一个包含姓名数据的文本文件:

John
Ham
Joe
Tope
Nalawas

我希望 php 查找 Joe 并将其从列表中删除。任何的想法?

我的想法:

<?php
$lines = file('user.txt');
$word = '';
$result = '';

foreach($lines as $line) {
    if(substr($line) == 'joe') {
        $result .= $word."\n";
    } else {
        $result .= $line;
    }
}

file_put_contents('user.txt', $result);

?>

此代码无效我想使用 preg-replace

只需使用$result = str_replace('Joe','',$line);

提醒一下,这种方法适用于你提到的情况,但如果有像 "Joesephine" 这样的名字,它会产生一行:sephine

也可能想查看:strtolower() 比较这样的字符串以考虑不区分大小写的情况 http://php.net/manual/en/function.strtolower.php

这个效果很好。
但如前所述,Joesephine 也会被移除

$lines  = file('names.txt');
$search = 'joe';

$result = '';
foreach($lines as $line) {
    if(stripos($line, $search) === false) {
        $result .= $line;
    }
}
file_put_contents('names2.txt', $result);