使用 PHP 替换文本文件中的行 [英] Replace line in text file using PHP

查看:68
本文介绍了使用 PHP 替换文本文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下数据的文本文件:

I have a text file with the following data:

1_fjd
2_skd
3_fks

我想用 php 替换我的文本文件中的一部分.例如我想这样做:

I want to replace a part in my text file using php. For example I want to do this:

找到以2_"开头的那一行,并用2_word"替换它,所以'2_'之后的所有内容都被替换为:'word'.我怎样才能在 php 中做到这一点?

Find the line that starts with "2_" and replace it with "2_word", so everything after '2_' is being replaced by:'word'. How can I do this in php?

推荐答案

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

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

这篇关于使用 PHP 替换文本文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆