所需的解決方案:爲什麼它會在下一行的開始處添加文本,而不是在正確的末尾?
我用一個簡單的PHP腳本的工作應該:
- 添加「VALUE4 :::」在第一行的一個文件末尾
- 添加「 :::「在所有下一行的末尾
我在編程方面很努力,並且在這裏坐了兩天試圖找出答案。可能是一個小細節,或者它可能是完成這個任務的完全錯誤的方式。
這可能是錯誤的方法,或者可能是一個正則表達式問題?我真的不知道。
我懇請您幫助解決方案。
信息:
文件newstest.db看起來是這樣的:
ID:::value1:::value2:::value3:::
1:::My:::first:::line:::
2:::My:::second:::line:::
3:::Your:::third:::line:::
並使用該PHP腳本,我想使它看起來像這樣:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
問題:
到目前爲止,我還差點,但我很困惑,爲什麼它添加「VALUE4 :::」到開始秒線,然後添加「 :::「在所有其餘行的開頭(不是結尾)。
所以我得到類似如下的文件:
ID:::value1:::value2:::value3:::
value4:::1:::My:::first:::line:::
:::2:::My:::second:::line:::
:::3:::Your:::third:::line:::
我認爲:
$lineshere = 'Some text here:::';
$lines1 = $linehere.'value4:::';
將輸出 「有些文字在這裏::: VALUE4 :::」
可能問題是由於這種方式後續添加行嗎?
$lines = '';
$lines.= 'My test';
$lines.= ' is here';
echo $lines;
我是編程的新手,所以我可能使用了完全錯誤的函數tec來完成這項工作。
但是在這種情況下,它會在錯誤的地方添加空格或換行符/行結尾。
我對這個問題的解決方案嘗試:
<?php
// specify the file
$file_source="newstest.db";
// get the content of the file
$newscontent = file($file_source, true);
//set a start value (clear memory)
$lines ='';
// get each line and treat it line by line.
foreach ($newscontent as $line_num => $linehere) {
// add "value4:::" at the end of FIRST line only, and put it in memory $lines
if($line_num==0) {
$lines.= $linehere.'value4:::';
// Just to see what the line looks like
//echo 'First line: '.$lines.'<br /><br />';
}
// then add ":::" to the other lines and add them to memory $lines
if($line_num>0) {
$lines1 = $linehere.':::';
$lines.= $lines1;
//just look at the line
//echo 'Line #'.$line_num.': '.$lines1.'<br /><br />';
}
}
//Write new content to $file_source
$f = fopen($file_source, 'w');
fwrite($f,$lines);
fclose($f);
echo "// to show the results ar array<br /><br />";
$newscontentlook = file($file_source, true);
print_r(array_values($newscontentlook));
?>
正如一個側面說明:您可能想看看使用十六進制編輯器,看看換行/回車字符和文件。 –
我相信,這是因爲$ linehere以換行符結束。 –
'$ newscontent = file($ file_source,true)''true'的目的是什麼;'?將其更改爲「FILE_IGNORE_NEW_LINES」,它應該可以工作。 – ClasG