因此,從你的描述,這是應該做的(我用PHP的代碼,你標記它你的問題):
打開批處理文件作爲一個字符串。
$fileTXT = file_get_contents($path_to_your_file, FILE_USE_INCLUDE_PATH);
(更換$path_to_your_file
一起,你要更新的文件的相對路徑)
更換輸入 - 字在這裏與新輸入的所有實例:
$fileTXT = str_replace("INPUT-WORD-HERE", $textToReplace, $fileTXT);
但事情並非如此簡單。這比起初看起來有點棘手,因爲INPUT-WORD-HERE不會一次一次地顯示相同的文本。我們需要創建一個通用的腳本,它將取代任何值:
$pos1 = strpos($fileTXT, "http://www.example.com/");
$textFrom = substr($fileTXT, $pos1+23, strpos($fileTXT, "/", $pos1 + 23) - $pos1 - 23);
$fileTXT = str_replace("http://www.example.com/" . $textFrom . "/", "http://www.example.com/" . $textTo . "/", $fileTXT);
我更換整個網址,以避免可能出現的問題,如果先前輸入-WORD-HERE值相匹配的文件在不同的文本(例如:「example」或「PAGE」)
保存文件。
file_put_contents($path_to_your_file, $fileTXT);
最後的代碼如下所示:
<?php
// here the relative path to your batch file
$filename = "myfile.txt";
// replace $_GET["txt"] for the name of the input that will have the new value. You can use $_POST too
$textTo = $_GET["txt"];
// read the content of the file into a string
$fileTXT = file_get_contents($filename, FILE_USE_INCLUDE_PATH);
// get the word to be replace from the URL (23 is the length of "http://www.example.com/", you'll need to change that number to fit the URL that you place there)
$pos1 = strpos($fileTXT, "http://www.example.com/");
$textFrom = substr($fileTXT, $pos1+23, strpos($fileTXT, "/", $pos1 + 23) - $pos1 - 23);
$fileTXT = str_replace("http://www.example.com/" . $textFrom . "/", "http://www.example.com/" . $textTo . "/", $fileTXT);
// overwrite the content of the file
file_put_contents($filename, $fileTXT);
正如我在評論中規定,這種解決方案存在一些危險,不應與普通用戶(使用你說這是好的,因爲它只爲你)。如果您更改它以便普通用戶可以訪問它,則應該對輸入進行預處理和消毒。
由於用戶請求,這是一個如何的HTML表單可以是一個簡單的例子:
<form method="get" action="YOUR_PHP_FILE_WITH_THE_ABOVE_CODE">
<label for="txt">
Write here the new name:
<input type="text" name="txt" id="txt" />
</label>
<input type="submit" value="Make Changes" />
</form>
你只需要確保文本輸入具有相同的名稱作爲參數您在$_GET
(或$_POST
,但您需要將表格更改爲method="post"
)中閱讀。
JavaScript不允許將文件讀寫到客戶端計算機。如果你想在服務器上存儲數據,你可以使用服務器端語言,如PHP,Node.js或ASP.NET –
這個txt文件位於客戶端計算機上嗎? –
我將txt文件存儲在服務器中以供稍後使用。 –