使用PHP在文本文件中的特定行插入内容

Cli*_*ote 1 php file-io

我有一个名为config.php的文件,我希望它保持原样,但是在第4行有一行说:

$config['url'] = '...could be anything here';
Run Code Online (Sandbox Code Playgroud)

我只想用我自己提供的url替换第4行的内容$config['ur'],有没有办法在PHP中执行此操作?

Luc*_*man 6

既然您知道确切的行号,可能最准确的方法是使用file(),它返回一行数组:

$contents = file('config.php');
$contents[3] = '$config[\'url\'] = "whateva"'."\n";
$outfile = fopen('config.php','w');
fwrite($outfile,implode('',$contents));
fclose($outfile);
Run Code Online (Sandbox Code Playgroud)