簡體   English   中英

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

[英]Inserting something at a particular line in a text file using PHP

我有一個名為config.php的文件,我希望它保持原樣,但是在第4行上有一行這樣寫:

$config['url'] = '...could be anything here';

我只想用為$config['ur']提供的自己的網址替換第4行的內容,有沒有辦法在PHP中做到這一點?

因為您知道確切的行號,所以執行此操作的最准確的方法可能是使用file(),它返回一個行數組:

$contents = file('config.php');
$contents[3] = '$config[\'url\'] = "whateva"'."\n";
$outfile = fopen('config.php','w');
fwrite($outfile,implode('',$contents));
fclose($outfile);
$myline = "my confg line";

$file = "config.php";

$contents = file($file);
$contents[3] = $myLine;
$file = implode("\n", $contents);

要么創建另一個配置(myconfig.php)。 包括原始文件並覆蓋該選項。 包括myconfig.php而不是原始的。

要么

轉到包含配置的位置(您確實對所有包含使用了單個位置嗎?)並在那里設置config選項。

   include "config.php"
   $config['url'] = "my_leet_urlz";

您可以讀取文件,在適當的字符串上使用str_replace或preg_replace,然后將文件寫回到自身。

$filename = "/path/to/file/filename";
$configFile = file($filename);
$configFile[3] = '$'."config['url'] = '...could be anything here';";
file_put_contents($filename  ,$configFile);

如果只有一個$ config ['url'],請使用preg_replace() http://us.php.net/preg_replace

像這樣:$ pattern ='\\ $ config ['url'] =“ [\\ d \\ w \\ s] *”'$ file_contents = preg_replace($ pattern,$ config ['url'] =“ my_leet_urlz”;,$ file_contents);

您需要修復這種模式,因為我是regex的新手,我知道這是不對的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM