且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 PHP 替换文本文件中的行

更新时间:2023-02-23 17:34:38

您不需要正则表达式.请尝试以下操作:

You don't need a regex for this. Try the following:

  • 使用 file() 将文件加载到数组中并循环遍历各行
  • 检查字符串是否以2_
  • 开头
  • 如果是,则将其替换为输入 $word 并将其连接到 $result 字符串
  • 如果没有,只需将其连接到 $result 字符串
  • 使用file_get_contents()并将结果写入文件
  • Load the file into an array using file() and loop through the lines
  • Check if the string starts with 2_
  • If it does, replace it with the input $word and concatenate it to the $result string
  • If if doesn't, simply concatenate it to the $result string
  • Use file_get_contents() and write the result to the file

代码:

$lines = file('file.txt');
$word = 'word';
$result = '';

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

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

现在,如果替换发生,那么 file.txt 将包含如下内容:

Now, if the replace took place, then file.txt would contain the something like:

1_fjd
2_word
3_fks